'use client'

/**
 * 報表 Page — 完整處置統計儀表板
 * ====================================
 * Sprint 4 E1: 告警處置統計主戰場
 *
 * 串接:
 *   GET /api/v1/stats/incident-summary
 *   GET /api/v1/stats/resolution-stats
 *   GET /api/v1/stats/disposition (Sprint 4 新增)
 *
 * 專案鐵律: 禁止假數據！無資料顯示 '--'
 * i18n: 100% next-intl
 *
 * 2026-04-02 Claude Code — 初版
 * 2026-04-07 Claude Code — Sprint 4 E1 處置統計升級
 */

import { useEffect, useState, useMemo } from 'react'
import { useTranslations } from 'next-intl'
import { AppLayout } from '@/components/layout'
import { cn } from '@/lib/utils'
import { Bot, UserCheck, Wrench, Sparkles, TrendingUp, BarChart3, Inbox, RefreshCw } from 'lucide-react'

const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? ''

// =============================================================================
// Types (對齊後端 DispositionResponse)
// =============================================================================

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

interface DispositionByAnomaly {
  anomaly_key: string
  alert_name: string
  disposition: DispositionSummary
}

interface DispositionResponse {
  summary: DispositionSummary
  by_anomaly: DispositionByAnomaly[]
}

interface IncidentSummary {
  total?: number
  resolved?: number
  unresolved?: number
}

interface ResolutionStats {
  resolutionRate?: number
  avgResolutionTime?: string | number
}

// =============================================================================
// Page
// =============================================================================

export default function ReportsPage({ params }: { params: { locale: string } }) {
  const t = useTranslations('reports')
  const tc = useTranslations('common')
  const [summary, setSummary] = useState<IncidentSummary | null>(null)
  const [resolution, setResolution] = useState<ResolutionStats | null>(null)
  const [disposition, setDisposition] = useState<DispositionResponse | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(false)

  const fetchAll = () => {
    setLoading(true)
    setError(false)
    Promise.all([
      fetch(`${API_BASE}/api/v1/stats/incident-summary`).then(r => r.json()).catch(() => null),
      fetch(`${API_BASE}/api/v1/stats/resolution-stats`).then(r => r.json()).catch(() => null),
      fetch(`${API_BASE}/api/v1/stats/disposition`).then(r => r.json()).catch(() => null),
    ])
      .then(([s, r, d]) => {
        setSummary(s)
        setResolution(r)
        setDisposition(d)
      })
      .catch(() => setError(true))
      .finally(() => setLoading(false))
  }

  useEffect(() => { fetchAll() }, [])

  const ds = disposition?.summary

  // 處置分佈百分比 (用於堆疊條)
  const pcts = useMemo(() => {
    if (!ds || ds.total === 0) return null
    const t = ds.total
    return {
      auto: Math.round((ds.auto_repair / t) * 100),
      human: Math.round((ds.human_approved / t) * 100),
      manual: Math.round((ds.manual_resolved / t) * 100),
      cold: Math.round((ds.cold_start_trust / t) * 100),
    }
  }, [ds])

  return (
    <AppLayout locale={params.locale}>
      <div className="p-6 space-y-6 min-h-full">

        {/* Header */}
        <div className="flex items-start justify-between">
          <div>
            <h1 className="text-lg font-semibold tracking-tight">{t('title')}</h1>
            <p className="text-xs text-muted-foreground mt-0.5">{t('subtitle')}</p>
          </div>
          <button
            onClick={fetchAll}
            className="p-2 rounded-lg hover:bg-muted transition-colors"
            title={tc('refresh')}
          >
            <RefreshCw className={cn('w-4 h-4 text-muted-foreground', loading && 'animate-spin')} />
          </button>
        </div>

        {loading && (
          <div className="text-center py-16 text-muted-foreground text-sm">{tc('loading')}</div>
        )}

        {!loading && error && (
          <div className="text-center py-16 text-red-500 text-sm">{t('fetchError')}</div>
        )}

        {!loading && !error && (
          <>
            {/* ── 頂部 KPI 3 卡 ── */}
            <div className="grid grid-cols-3 gap-4">
              <KPICard
                icon={<BarChart3 className="w-5 h-5 text-blue-500" />}
                label={t('totalDispositions')}
                value={ds?.total ?? '--'}
                color="text-blue-500"
              />
              <KPICard
                icon={<Bot className="w-5 h-5 text-green-500" />}
                label={t('autoRate')}
                value={ds ? `${Math.round(ds.auto_rate * 100)}%` : '--'}
                color="text-green-500"
              />
              <KPICard
                icon={<UserCheck className="w-5 h-5 text-orange-500" />}
                label={t('humanRate')}
                value={ds ? `${Math.round(ds.human_rate * 100)}%` : '--'}
                color="text-orange-500"
              />
            </div>

            {/* ── 四大計數卡片 ── */}
            <div className="grid grid-cols-4 gap-3">
              <DispositionCard
                icon={<Bot className="w-4 h-4" />}
                label={t('autoRepair')}
                count={ds?.auto_repair ?? 0}
                color="text-green-500"
                bg="bg-green-500/10"
                border="border-green-500/25"
              />
              <DispositionCard
                icon={<UserCheck className="w-4 h-4" />}
                label={t('humanApproved')}
                count={ds?.human_approved ?? 0}
                color="text-orange-500"
                bg="bg-orange-500/10"
                border="border-orange-500/25"
              />
              <DispositionCard
                icon={<Wrench className="w-4 h-4" />}
                label={t('manualResolved')}
                count={ds?.manual_resolved ?? 0}
                color="text-purple-500"
                bg="bg-purple-500/10"
                border="border-purple-500/25"
              />
              <DispositionCard
                icon={<Sparkles className="w-4 h-4" />}
                label={t('coldStartTrust')}
                count={ds?.cold_start_trust ?? 0}
                color="text-blue-500"
                bg="bg-blue-500/10"
                border="border-blue-500/25"
              />
            </div>

            {/* ── 堆疊分佈條 ── */}
            {pcts && (
              <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="flex h-4 rounded-full overflow-hidden">
                  {pcts.auto > 0 && <div className="bg-green-500 transition-all" style={{ width: `${pcts.auto}%` }} title={`${t('autoRepair')}: ${pcts.auto}%`} />}
                  {pcts.cold > 0 && <div className="bg-blue-500 transition-all" style={{ width: `${pcts.cold}%` }} title={`${t('coldStartTrust')}: ${pcts.cold}%`} />}
                  {pcts.human > 0 && <div className="bg-orange-500 transition-all" style={{ width: `${pcts.human}%` }} title={`${t('humanApproved')}: ${pcts.human}%`} />}
                  {pcts.manual > 0 && <div className="bg-purple-500 transition-all" style={{ width: `${pcts.manual}%` }} title={`${t('manualResolved')}: ${pcts.manual}%`} />}
                </div>
                <div className="flex items-center gap-4 mt-2 text-[10px] text-muted-foreground">
                  <span className="flex items-center gap-1"><span className="w-2 h-2 rounded-full bg-green-500" />{t('autoRepair')} {pcts.auto}%</span>
                  <span className="flex items-center gap-1"><span className="w-2 h-2 rounded-full bg-blue-500" />{t('coldStartTrust')} {pcts.cold}%</span>
                  <span className="flex items-center gap-1"><span className="w-2 h-2 rounded-full bg-orange-500" />{t('humanApproved')} {pcts.human}%</span>
                  <span className="flex items-center gap-1"><span className="w-2 h-2 rounded-full bg-purple-500" />{t('manualResolved')} {pcts.manual}%</span>
                </div>
              </div>
            )}

            {/* ── 按異常類型明細 ── */}
            {disposition?.by_anomaly && disposition.by_anomaly.length > 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('byAnomalyType')}</p>
                <table className="w-full">
                  <thead>
                    <tr className="text-[10px] text-muted-foreground uppercase tracking-wider">
                      <th className="text-left pb-2 font-medium">{t('anomalyKey')}</th>
                      <th className="text-right pb-2 font-medium">{t('autoRepair')}</th>
                      <th className="text-right pb-2 font-medium">{t('humanApproved')}</th>
                      <th className="text-right pb-2 font-medium">{t('manualResolved')}</th>
                      <th className="text-right pb-2 font-medium">{t('coldStartTrust')}</th>
                      <th className="text-right pb-2 font-medium">{t('totalDispositions')}</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border">
                    {disposition.by_anomaly.map(item => (
                      <tr key={item.anomaly_key}>
                        <td className="py-2 text-xs font-mono">{item.alert_name || item.anomaly_key.slice(0, 12)}</td>
                        <td className="py-2 text-xs text-right text-green-500 font-semibold">{item.disposition.auto_repair}</td>
                        <td className="py-2 text-xs text-right text-orange-500 font-semibold">{item.disposition.human_approved}</td>
                        <td className="py-2 text-xs text-right text-purple-500 font-semibold">{item.disposition.manual_resolved}</td>
                        <td className="py-2 text-xs text-right text-blue-500 font-semibold">{item.disposition.cold_start_trust}</td>
                        <td className="py-2 text-xs text-right font-bold">{item.disposition.total}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}

            {/* ── 既有: 事件摘要 ── */}
            <div className="grid grid-cols-2 gap-4">
              <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('incidentSummary')}</p>
                <div className="grid grid-cols-3 gap-3">
                  <MiniStat label={t('total')} value={summary?.total ?? '--'} />
                  <MiniStat label={t('resolved')} value={summary?.resolved ?? '--'} />
                  <MiniStat label={t('unresolved')} value={summary?.unresolved ?? '--'} />
                </div>
              </div>
              <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('resolutionStats')}</p>
                <div className="grid grid-cols-2 gap-3">
                  <MiniStat label={t('resolutionRate')} value={resolution?.resolutionRate != null ? `${resolution.resolutionRate}%` : '--'} />
                  <MiniStat label={t('avgResolutionTime')} value={resolution?.avgResolutionTime ?? '--'} />
                </div>
              </div>
            </div>

            {/* 無資料提示 */}
            {!ds || ds.total === 0 ? (
              <div className="rounded-xl border border-border bg-card p-8 flex flex-col items-center justify-center text-muted-foreground">
                <Inbox className="w-8 h-8 mb-2 opacity-40" />
                <p className="text-sm">{t('noData')}</p>
              </div>
            ) : null}
          </>
        )}
      </div>
    </AppLayout>
  )
}

// =============================================================================
// Sub-components
// =============================================================================

function KPICard({ icon, label, value, color }: { icon: React.ReactNode; label: string; value: string | number; color: string }) {
  return (
    <div className="rounded-xl border border-border bg-card p-5 flex items-center gap-4">
      <div className="w-10 h-10 rounded-lg bg-muted flex items-center justify-center flex-shrink-0">
        {icon}
      </div>
      <div>
        <p className={cn('text-2xl font-bold tabular-nums', color)}>{value}</p>
        <p className="text-[10px] uppercase tracking-wider text-muted-foreground mt-0.5">{label}</p>
      </div>
    </div>
  )
}

function DispositionCard({ icon, label, count, color, bg, border }: { icon: React.ReactNode; label: string; count: number; color: string; bg: string; border: string }) {
  return (
    <div className={cn('rounded-xl border p-4 text-center', border, bg)}>
      <div className={cn('flex items-center justify-center gap-1.5 mb-2', color)}>
        {icon}
        <span className="text-[10px] font-bold uppercase tracking-wider">{label}</span>
      </div>
      <p className={cn('text-3xl font-bold tabular-nums', color)}>{count}</p>
    </div>
  )
}

function MiniStat({ label, value }: { label: string; value: string | number }) {
  return (
    <div className="text-center">
      <p className="text-xl font-bold tabular-nums">{value}</p>
      <p className="text-[10px] text-muted-foreground mt-0.5">{label}</p>
    </div>
  )
}
