'use client'

/**
 * NeuralStats - 統計 & 歷史面板
 * ================================
 * 5 KPI + 執行路徑分佈 + Playbook 排名 + 時間軸
 *
 * 2026-04-07 Claude Code: Sprint F 打假行動 — 移除所有假資料常數
 * 專案鐵律: 所有數據從 stats/playbooks/history props 計算，禁止寫死！
 */

import { useMemo } from 'react'
import { useTranslations } from 'next-intl'
import { cn } from '@/lib/utils'
import { Bot, Inbox, Server, Settings } from 'lucide-react'
import type { LucideIcon } from 'lucide-react'
import type { AutoRepairStats, PlaybookItem, RepairHistoryItem } from './types'

interface DispositionSummary {
  total: number
  auto_repair: number
  human_approved: number
  manual_resolved: number
  cold_start_trust: number
  auto_rate: number
}

interface Props {
  stats: AutoRepairStats | null
  playbooks: PlaybookItem[]
  history: RepairHistoryItem[]
  pendingCount: number
  disposition?: DispositionSummary | null
}

const TYPE_BADGE: Record<string, string> = {
  kubectl:  'bg-blue-500/10 text-blue-500 border border-blue-500/25',
  ansible:  'bg-purple-500/10 text-purple-500 border border-purple-500/25',
  openclaw: 'bg-orange-500/10 text-orange-500 border border-orange-500/25',
}

const SCHEME_STYLE: Record<string, { Icon: LucideIcon; color: string; textColor: string; bg: string }> = {
  'kubectl://':  { Icon: Server,   color: 'bg-blue-500',   textColor: 'text-blue-500',   bg: 'bg-blue-500/10' },
  'openclaw://': { Icon: Bot,      color: 'bg-orange-500', textColor: 'text-orange-500', bg: 'bg-orange-500/10' },
  'ansible://':  { Icon: Settings, color: 'bg-purple-500', textColor: 'text-purple-500', bg: 'bg-purple-500/10' },
}

export function NeuralStats({ stats, playbooks, history, pendingCount, disposition }: Props) {
  const t = useTranslations('neuralCommand')

  // 從 history 聚合 scheme 分佈
  const schemeStats = useMemo(() => {
    const counts: Record<string, { count: number; successCount: number }> = {}
    for (const item of history) {
      const scheme = item.uri_scheme
      if (!counts[scheme]) counts[scheme] = { count: 0, successCount: 0 }
      counts[scheme].count++
      if (item.status === 'success') counts[scheme].successCount++
    }
    const total = history.length || 1
    return Object.entries(counts).map(([scheme, { count, successCount }]) => ({
      scheme,
      ...(SCHEME_STYLE[scheme] ?? SCHEME_STYLE['kubectl://']),
      count,
      rate: count > 0 ? Math.round((successCount / count) * 100) : 0,
      pct: Math.round((count / total) * 100),
    })).sort((a, b) => b.count - a.count)
  }, [history])

  // 從 playbooks 排序 (按成功率，有執行次數的優先)
  const playbookRankings = useMemo(() => {
    return playbooks
      .filter(p => p.success_count + p.failure_count > 0)
      .map(p => {
        const total = p.success_count + p.failure_count
        return {
          name: p.name,
          type: p.tags.includes('ansible') ? 'ansible' : p.tags.includes('openclaw') ? 'openclaw' : 'kubectl',
          rate: total > 0 ? Math.round((p.success_count / total) * 100) : 0,
          count: total,
        }
      })
      .sort((a, b) => b.count - a.count)
      .slice(0, 8)
  }, [playbooks])

  // 從 history 計算平均時長
  const avgDuration = useMemo(() => {
    const durations = history.filter(h => h.duration_ms != null).map(h => h.duration_ms!)
    if (durations.length === 0) return '--'
    const avg = durations.reduce((a, b) => a + b, 0) / durations.length
    return `${(avg / 1000).toFixed(1)}s`
  }, [history])

  const successRate = stats?.overall_success_rate ?? null
  const totalExec = stats?.total_executions ?? null

  const KPIs = [
    { label: t('kpiSuccessRate'),  value: successRate != null ? `${Math.round(successRate * 100)}%` : '--', color: 'text-green-500' },
    { label: t('kpiTotalExec'),    value: totalExec ?? '--',                                                 color: 'text-blue-500' },
    { label: t('kpiPlaybooks'),    value: stats?.approved_playbooks ?? '--',                                 color: 'text-orange-500' },
    { label: t('kpiAvgDuration'),  value: avgDuration,                                                       color: 'text-yellow-500' },
    { label: t('kpiPendingAppr'),  value: pendingCount,                                                      color: 'text-purple-500' },
  ]

  return (
    <div className="p-6 space-y-5">

      {/* ── KPI strip ── */}
      <div className="grid grid-cols-5 gap-3">
        {KPIs.map(({ label, value, color }) => (
          <div key={label} className="rounded-xl border border-border bg-card p-4 text-center">
            <p className={cn('text-3xl font-bold tabular-nums tracking-tight', color)}>{value}</p>
            <p className="text-[10px] uppercase tracking-wider text-muted-foreground mt-1">{label}</p>
          </div>
        ))}
      </div>

      {/* ── 處置分佈 (Sprint 4 E4) ── */}
      {disposition && disposition.total > 0 && (
        <div className="rounded-xl border border-border bg-card p-4">
          <p className="text-xs font-bold uppercase tracking-wider text-muted-foreground mb-3">{t('dispositionBreakdown')}</p>
          <div className="grid grid-cols-4 gap-2">
            {[
              { label: t('dispositionAuto'), value: disposition.auto_repair, color: 'text-green-500', bg: 'bg-green-500/10', border: 'border-green-500/25' },
              { label: t('dispositionHuman'), value: disposition.human_approved, color: 'text-orange-500', bg: 'bg-orange-500/10', border: 'border-orange-500/25' },
              { label: t('dispositionManual'), value: disposition.manual_resolved, color: 'text-purple-500', bg: 'bg-purple-500/10', border: 'border-purple-500/25' },
              { label: t('dispositionCold'), value: disposition.cold_start_trust, color: 'text-blue-500', bg: 'bg-blue-500/10', border: 'border-blue-500/25' },
            ].map(d => (
              <div key={d.label} className={cn('rounded-lg border p-3 text-center', d.border, d.bg)}>
                <p className={cn('text-[10px] font-bold uppercase tracking-wider', d.color)}>{d.label}</p>
                <p className={cn('text-2xl font-bold tabular-nums mt-1', d.color)}>{d.value}</p>
              </div>
            ))}
          </div>
          <p className="text-[10px] text-muted-foreground text-center mt-2">
            {t('autoRateLabel')}: {Math.round(disposition.auto_rate * 100)}%
          </p>
        </div>
      )}

      <div className="grid grid-cols-2 gap-4">

        {/* ── Scheme breakdown ── */}
        <div className="rounded-xl border border-border bg-card p-4">
          <p className="text-xs font-bold uppercase tracking-wider text-muted-foreground mb-4">{t('schemeBreakdown')}</p>
          {schemeStats.length > 0 ? (
            <div className="space-y-3">
              {schemeStats.map(s => {
                const SchemeIcon = s.Icon
                return (
                <div key={s.scheme} className="flex items-center gap-3">
                  <span className={cn('flex h-6 w-6 items-center justify-center rounded-md', s.bg)}>
                    <SchemeIcon className={cn('h-3.5 w-3.5', s.textColor)} aria-hidden="true" />
                  </span>
                  <span className={cn('text-xs font-semibold w-24 font-mono', s.textColor)}>{s.scheme}</span>
                  <div className="flex-1 h-1.5 rounded-full bg-muted overflow-hidden">
                    <div className={cn('h-full rounded-full', s.color)} style={{ width: `${s.pct}%` }} />
                  </div>
                  <span className={cn('text-xs font-bold w-6 text-right', s.textColor)}>{s.count}</span>
                  <span className="text-xs text-muted-foreground w-8 text-right">{s.rate}%</span>
                </div>
                )
              })}
            </div>
          ) : (
            <div className="flex flex-col items-center justify-center py-8 text-muted-foreground">
              <Inbox className="w-5 h-5 mb-1 opacity-40" />
              <p className="text-[10px]">{t('noHistory')}</p>
            </div>
          )}
        </div>

        {/* ── Playbook ranking ── */}
        <div className="rounded-xl border border-border bg-card p-4">
          <p className="text-xs font-bold uppercase tracking-wider text-muted-foreground mb-3">{t('playbookRanking')}</p>
          {playbookRankings.length > 0 ? (
            <table className="w-full">
              <thead>
                <tr className="text-[10px] text-muted-foreground uppercase tracking-wider">
                  <th className="text-left pb-2 font-medium">{t('thName')}</th>
                  <th className="text-left pb-2 font-medium">{t('thType')}</th>
                  <th className="text-left pb-2 font-medium">{t('thRate')}</th>
                  <th className="text-right pb-2 font-medium">{t('thCount')}</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-border">
                {playbookRankings.map(pb => (
                  <tr key={pb.name}>
                    <td className="py-2 text-xs font-semibold pr-2">{pb.name}</td>
                    <td className="py-2 pr-2">
                      <span className={cn('text-[10px] font-bold px-1.5 py-0.5 rounded', TYPE_BADGE[pb.type] ?? TYPE_BADGE['kubectl'])}>
                        {pb.type}
                      </span>
                    </td>
                    <td className="py-2 pr-2">
                      <div className="flex items-center gap-1.5">
                        <div className="w-12 h-1 rounded-full bg-muted overflow-hidden">
                          <div className="h-full rounded-full bg-green-500" style={{ width: `${pb.rate}%` }} />
                        </div>
                        <span className="text-[10px] font-bold text-green-500">{pb.rate}%</span>
                      </div>
                    </td>
                    <td className="py-2 text-xs text-right text-muted-foreground">{pb.count}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          ) : (
            <div className="flex flex-col items-center justify-center py-8 text-muted-foreground">
              <Inbox className="w-5 h-5 mb-1 opacity-40" />
              <p className="text-[10px]">{t('noPlaybooks')}</p>
            </div>
          )}
        </div>
      </div>

      {/* ── History timeline ── */}
      <div className="rounded-xl border border-border bg-card p-4">
        <p className="text-xs font-bold uppercase tracking-wider text-muted-foreground mb-4">{t('historyTimeline')}</p>
        {history.length > 0 ? (
          <div className="space-y-0 divide-y divide-border">
            {history.map(item => {
              const elapsed = Math.round((Date.now() - new Date(item.executed_at).getTime()) / 60000)
              const isSuccess = item.status === 'success'
              const isPending = item.status === 'pending_approval'
              const isFailed  = item.status === 'failed'

              return (
                <div key={item.id} className="flex gap-3 py-3">
                  {/* Timeline dot */}
                  <div className="flex flex-col items-center pt-1 flex-shrink-0">
                    <div className={cn('w-2.5 h-2.5 rounded-full', {
                      'bg-green-500': isSuccess,
                      'bg-orange-500': isPending,
                      'bg-red-500': isFailed,
                      'bg-blue-500': item.status === 'running',
                    })} />
                    <div className="w-px flex-1 bg-border mt-1" />
                  </div>

                  {/* Content */}
                  <div className="flex-1 min-w-0 pb-1">
                    <div className="flex items-center gap-2 flex-wrap">
                      <p className="text-sm font-semibold">
                        {item.playbook_name}
                      </p>
                    </div>
                    <div className="flex items-center gap-2 mt-1 flex-wrap">
                      <span className="text-[10px] text-muted-foreground">{elapsed}m {t('ago')}</span>
                      <code className="text-[10px] bg-muted px-1.5 py-0.5 rounded font-mono text-muted-foreground">
                        {item.uri_scheme}{item.command.replace(/^[a-z]+:\/\//, '')}
                      </code>
                      {item.duration_ms && (
                        <span className="text-[10px] font-semibold text-green-500">
                          {(item.duration_ms / 1000).toFixed(1)}s
                        </span>
                      )}
                      {item.rag_confidence && (
                        <span className="text-[10px] text-muted-foreground">
                          RAG {item.rag_confidence.toFixed(2)}
                        </span>
                      )}
                      {isPending && (
                        <span className="text-[10px] text-orange-500 font-medium">{t('waitingApproval')}</span>
                      )}
                      {isFailed && item.error && (
                        <span className="text-[10px] text-red-400">{item.error}</span>
                      )}
                    </div>
                  </div>
                </div>
              )
            })}
          </div>
        ) : (
          <div className="flex flex-col items-center justify-center py-8 text-muted-foreground">
            <Inbox className="w-6 h-6 mb-2 opacity-40" />
            <p className="text-xs">{t('noHistory')}</p>
          </div>
        )}
      </div>
    </div>
  )
}
