'use client'

// 2026-04-26 P2.5 by Claude — AIOps Timeline
// ============================================================
// TimelineStageDetails — 展開的詳情區塊
// 每個 stage 有自己的展開格式
// ============================================================

import { useTranslations } from 'next-intl'
import { EvidenceViewer } from './EvidenceViewer'
import { cn } from '@/lib/utils'
import type {
  StageType,
  StageData,
  AlertStageData,
  DiagnoseStageData,
  DecideStageData,
  ExecuteStageData,
  VerifyStageData,
  LearnStageData,
} from './types'

interface TimelineStageDetailsProps {
  stage: StageType
  data: StageData
}

// ----- Helper Components -----

function MetaRow({ label, value, mono }: { label: string; value: React.ReactNode; mono?: boolean }) {
  return (
    <div className="flex items-start gap-2 py-1 border-b border-nothing-gray-100 last:border-0">
      <span className="w-32 flex-shrink-0 text-[11px] font-body text-nothing-gray-400 uppercase tracking-wider pt-0.5">
        {label}
      </span>
      <span className={cn('flex-1 text-xs font-body text-nothing-black break-all', mono && 'font-mono')}>
        {value}
      </span>
    </div>
  )
}

function LabelBadge({ label, value }: { label: string; value: string }) {
  return (
    <div className="inline-flex items-center gap-1 px-2 py-0.5 rounded bg-nothing-gray-100 border border-nothing-gray-200">
      <span className="text-[10px] font-body text-nothing-gray-400">{label}:</span>
      <span className="text-[10px] font-body font-medium text-nothing-black">{value}</span>
    </div>
  )
}

function ConfidenceBar({ value, threshold }: { value: number; threshold: number }) {
  const t = useTranslations('aiopsTimeline')
  const pct = Math.min(100, Math.round(value * 100))
  const isAbove = value >= threshold

  return (
    <div className="mt-1">
      <div className="h-1.5 bg-nothing-gray-100 rounded-full overflow-hidden">
        <div
          className={cn(
            'h-full rounded-full transition-all',
            isAbove ? 'bg-status-healthy' : 'bg-status-warning'
          )}
          style={{ width: `${pct}%` }}
          role="progressbar"
          aria-valuenow={pct}
          aria-valuemin={0}
          aria-valuemax={100}
        />
      </div>
      <div className="flex items-center justify-between mt-1">
        <span className="text-[10px] font-body text-nothing-gray-400">
          {pct}%
        </span>
        <span className="text-[10px] font-body text-nothing-gray-400">
          {t('stageDetails.decide.confidenceThreshold', { value: Math.round(threshold * 100) })}
        </span>
      </div>
    </div>
  )
}

function TrustBar({ before, after }: { before: number; after: number }) {
  const delta = after - before
  return (
    <div className="flex items-center gap-2">
      <span className="text-xs font-body tabular-nums text-nothing-gray-500">{(before * 100).toFixed(0)}%</span>
      <div className="flex-1 h-1.5 bg-nothing-gray-100 rounded-full overflow-hidden relative">
        <div
          className="h-full bg-nothing-gray-300 rounded-full"
          style={{ width: `${before * 100}%` }}
        />
        <div
          className="absolute top-0 h-full bg-status-healthy rounded-full"
          style={{ left: `${before * 100}%`, width: `${delta * 100}%` }}
        />
      </div>
      <span className="text-xs font-body tabular-nums font-medium text-status-healthy">
        {(after * 100).toFixed(0)}%
      </span>
    </div>
  )
}

// ----- Stage-specific renderers -----

function AlertDetails({ data }: { data: AlertStageData }) {
  const t = useTranslations('aiopsTimeline')
  return (
    <div className="space-y-0.5">
      <MetaRow label={t('stageDetails.alert.name')} value={data.alert_name} />
      <MetaRow label={t('stageDetails.alert.rule')} value={<span className="font-mono">{data.rule_matched}</span>} />
      {data.raw_value && (
        <MetaRow
          label={t('stageDetails.alert.value')}
          value={
            <span className="font-bold text-status-critical">{data.raw_value}
              {data.threshold && <span className="font-normal text-nothing-gray-400 ml-1">/ {data.threshold}</span>}
            </span>
          }
        />
      )}
      {Object.keys(data.labels).length > 0 && (
        <div className="py-1">
          <span className="text-[11px] font-body text-nothing-gray-400 uppercase tracking-wider">
            {t('stageDetails.alert.labels')}
          </span>
          <div className="flex flex-wrap gap-1 mt-1.5">
            {Object.entries(data.labels).map(([k, v]) => (
              <LabelBadge key={k} label={k} value={v} />
            ))}
          </div>
        </div>
      )}
    </div>
  )
}

function DiagnoseDetails({ data }: { data: DiagnoseStageData }) {
  const t = useTranslations('aiopsTimeline')
  return (
    <div className="space-y-2">
      <MetaRow label={t('stageDetails.diagnose.investigator')} value={data.investigator} />
      <div className="py-1">
        <span className="text-[11px] font-body text-nothing-gray-400 uppercase tracking-wider">
          {t('stageDetails.diagnose.tools_used')}
        </span>
        <div className="flex flex-wrap gap-1 mt-1.5">
          {data.mcp_tools_used.map((tool) => (
            <span key={tool} className="px-2 py-0.5 rounded bg-claw-blue/10 border border-claw-blue/20 text-[10px] font-mono text-claw-blue">
              {tool}
            </span>
          ))}
        </div>
      </div>
      <MetaRow label={t('stageDetails.diagnose.hypothesis')} value={data.root_cause_hypothesis} />
      <div className="pt-1">
        <span className="text-[11px] font-body text-nothing-gray-400 uppercase tracking-wider">
          {t('stageDetails.diagnose.evidence')}
        </span>
        <EvidenceViewer dimensions={data.dimensions} />
      </div>
    </div>
  )
}

function DecideDetails({ data }: { data: DecideStageData }) {
  const t = useTranslations('aiopsTimeline')
  return (
    <div className="space-y-0.5">
      <MetaRow label={t('stageDetails.decide.engine')} value={data.engine} />
      <MetaRow label={t('stageDetails.decide.fusion')} value={data.fusion_method} />
      <div className="py-1">
        <span className="text-[11px] font-body text-nothing-gray-400 uppercase tracking-wider">
          {t('stageDetails.decide.confidence')}
        </span>
        <ConfidenceBar value={data.confidence} threshold={data.threshold_used} />
      </div>
      <MetaRow
        label={t('stageDetails.decide.auto_execute')}
        value={
          <span className={cn(
            'inline-flex items-center px-1.5 py-0.5 rounded text-[11px] font-body font-bold uppercase',
            data.auto_execute
              ? 'bg-status-healthy/10 text-status-healthy'
              : 'bg-status-warning/10 text-status-warning'
          )}>
            {data.auto_execute ? t('stageDetails.decide.auto_yes') : t('stageDetails.decide.auto_no')}
          </span>
        }
      />
      <MetaRow label={t('stageDetails.decide.playbook')} value={
        <span>{data.playbook_name} <span className="text-nothing-gray-400 font-mono">({data.playbook_id})</span></span>
      } />
      <div className="py-1 border-b border-nothing-gray-100">
        <span className="text-[11px] font-body text-nothing-gray-400 uppercase tracking-wider">
          {t('stageDetails.decide.decision')}
        </span>
        <p className="mt-1 text-xs font-mono text-nothing-black bg-nothing-gray-50 border border-nothing-gray-200 rounded px-2 py-1.5 break-all">
          {data.decision}
        </p>
      </div>
      <div className="py-1">
        <span className="text-[11px] font-body text-nothing-gray-400 uppercase tracking-wider">
          {t('stageDetails.decide.reasoning')}
        </span>
        <p className="mt-1 text-xs font-body text-nothing-gray-700 leading-relaxed">
          {data.reasoning}
        </p>
      </div>
      {data.alternate_decisions && data.alternate_decisions.length > 0 && (
        <div className="py-1">
          <span className="text-[11px] font-body text-nothing-gray-400 uppercase tracking-wider">
            {t('stageDetails.decide.alternates')}
          </span>
          <div className="mt-1.5 space-y-1">
            {data.alternate_decisions.map((alt, i) => (
              <div key={i} className="flex items-center gap-2 opacity-50">
                <div className="w-16 h-1 bg-nothing-gray-200 rounded-full overflow-hidden">
                  <div className="h-full bg-nothing-gray-400 rounded-full" style={{ width: `${alt.confidence * 100}%` }} />
                </div>
                <span className="text-[10px] font-mono text-nothing-gray-500 flex-1 truncate">{alt.decision}</span>
                <span className="text-[10px] font-body text-nothing-gray-400">{(alt.confidence * 100).toFixed(0)}%</span>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  )
}

function ExecuteDetails({ data }: { data: ExecuteStageData }) {
  const t = useTranslations('aiopsTimeline')
  return (
    <div className="space-y-0.5">
      <MetaRow label={t('stageDetails.execute.target')} value={data.target} />
      <MetaRow label={t('stageDetails.execute.executor')} value={data.executor} />
      <MetaRow label={t('stageDetails.execute.duration')} value={`${(data.duration_ms / 1000).toFixed(1)}s`} />
      <div className="py-1">
        <span className="text-[11px] font-body text-nothing-gray-400 uppercase tracking-wider">
          {t('stageDetails.execute.command')}
        </span>
        <pre className="mt-1 text-[11px] font-mono text-nothing-black bg-nothing-gray-900 text-nothing-white rounded px-3 py-2 overflow-x-auto whitespace-pre-wrap break-all text-[11px] leading-relaxed" style={{ color: '#e5e5e5' }}>
          {data.command}
        </pre>
      </div>
      {data.stdout && (
        <div className="py-1">
          <span className="text-[11px] font-body text-nothing-gray-400 uppercase tracking-wider">
            {t('stageDetails.execute.stdout')}
          </span>
          <pre className="mt-1 text-[11px] font-mono bg-nothing-gray-900 rounded px-3 py-2 overflow-x-auto whitespace-pre-wrap break-all leading-relaxed" style={{ color: '#86efac' }}>
            {data.stdout}
          </pre>
        </div>
      )}
      <MetaRow
        label={t('stageDetails.execute.exit_code')}
        value={
          <span className={cn(
            'font-mono font-bold',
            data.exit_code === 0 ? 'text-status-healthy' : 'text-status-critical'
          )}>
            {data.exit_code}
          </span>
        }
      />
    </div>
  )
}

function VerifyDetails({ data }: { data: VerifyStageData }) {
  const t = useTranslations('aiopsTimeline')
  const pct = Math.round((data.checks_passed / data.checks_total) * 100)
  return (
    <div className="space-y-0.5">
      <MetaRow label={t('stageDetails.verify.verifier')} value={data.verifier} />
      <MetaRow
        label={t('stageDetails.verify.outcome')}
        value={
          <span className={cn(
            'inline-flex items-center px-1.5 py-0.5 rounded text-[11px] font-body font-bold uppercase',
            data.outcome === 'SUCCESS' ? 'bg-status-healthy/10 text-status-healthy'
            : data.outcome === 'PARTIAL' ? 'bg-status-warning/10 text-status-warning'
            : 'bg-status-critical/10 text-status-critical'
          )}>
            {data.outcome}
          </span>
        }
      />
      <div className="py-1">
        <span className="text-[11px] font-body text-nothing-gray-400 uppercase tracking-wider">
          {t('stageDetails.verify.checks')}
        </span>
        <div className="flex items-center gap-2 mt-1.5">
          <div className="flex-1 h-1.5 bg-nothing-gray-100 rounded-full overflow-hidden">
            <div
              className={cn('h-full rounded-full', pct === 100 ? 'bg-status-healthy' : 'bg-status-warning')}
              style={{ width: `${pct}%` }}
            />
          </div>
          <span className="text-xs font-body tabular-nums text-nothing-black">
            {data.checks_passed}/{data.checks_total}
          </span>
        </div>
      </div>
      {data.trust_delta !== 0 && (
        <MetaRow
          label={t('stageDetails.verify.trust_delta')}
          value={
            <span className={cn('font-mono font-bold', data.trust_delta > 0 ? 'text-status-healthy' : 'text-status-critical')}>
              {data.trust_delta > 0 ? '+' : ''}{(data.trust_delta * 100).toFixed(0)}%
            </span>
          }
        />
      )}
      {data.notes && (
        <MetaRow label={t('stageDetails.verify.notes')} value={data.notes} />
      )}
    </div>
  )
}

function LearnDetails({ data }: { data: LearnStageData }) {
  const t = useTranslations('aiopsTimeline')
  return (
    <div className="space-y-0.5">
      <MetaRow label={t('stageDetails.learn.playbook')} value={<span className="font-mono">{data.playbook_id}</span>} />
      <div className="py-1">
        <span className="text-[11px] font-body text-nothing-gray-400 uppercase tracking-wider">
          {t('stageDetails.learn.trust_update')}
        </span>
        <div className="mt-2">
          <TrustBar before={data.trust_before} after={data.trust_after} />
        </div>
      </div>
      {data.km_entry_id && (
        <MetaRow label={t('stageDetails.learn.km_entry')} value={<span className="font-mono">{data.km_entry_id}</span>} />
      )}
      <MetaRow label={t('stageDetails.learn.summary')} value={data.learning_summary} />
    </div>
  )
}

// ----- Main export -----

export function TimelineStageDetails({ stage, data }: TimelineStageDetailsProps) {
  switch (stage) {
    case 'alert':    return <AlertDetails   data={data as AlertStageData} />
    case 'diagnose': return <DiagnoseDetails data={data as DiagnoseStageData} />
    case 'decide':   return <DecideDetails  data={data as DecideStageData} />
    case 'execute':  return <ExecuteDetails data={data as ExecuteStageData} />
    case 'verify':   return <VerifyDetails  data={data as VerifyStageData} />
    case 'learn':    return <LearnDetails   data={data as LearnStageData} />
    default:         return null
  }
}
