'use client'

/**
 * SloTab — SLO 儀表 Tab
 * ======================
 * 消費：GET /api/v1/ai/slo + GET /api/v1/ai/governance/summary?days=30
 *
 * 內容：
 *   1. 三 KPI 卡片（水平排列，mobile 堆疊）
 *   2. 30d 違反次數時序圖（Recharts BarChart stacked）
 *   3. 整體合規率副資訊
 *
 * @updated 2026-05-02 Claude Sonnet 4.6 — governance PR 3-5 填入真實內容
 */

import { useEffect, useState } from 'react'
import { useTranslations } from 'next-intl'
import { ShieldCheck, AlertTriangle } from 'lucide-react'
import { SloKpiCard, type SloMetric } from '@/components/governance/slo-kpi-card'
import { SloViolationChart, type ViolationDataPoint } from '@/components/governance/slo-violation-chart'
import { GlassCard } from '@/components/ui/glass-card'

// =============================================================================
// Config
// =============================================================================

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

// =============================================================================
// Types
// =============================================================================

interface SloApiResponse {
  metrics?: {
    decision_accuracy?: { current: number; target: number; status: string; sparkline?: number[] }
    km_growth_rate?:    { current: number; target: number; status: string; sparkline?: number[] }
    mcp_call_diversity?: { current: number; target: number; status: string; sparkline?: number[] }
  }
  overall_compliance?: number
  computed_at?: string
}

interface SummaryApiResponse {
  data?: ViolationDataPoint[]
  event_types?: string[]
  days?: number
}

// =============================================================================
// Helpers
// =============================================================================

function mapStatus(s: string): SloMetric['status'] {
  if (s === 'healthy') return 'healthy'
  if (s === 'warning') return 'warning'
  return 'critical'
}

function buildMetrics(api: SloApiResponse): SloMetric[] {
  const m = api.metrics ?? {}
  const names: Array<SloMetric['name']> = ['decision_accuracy', 'km_growth_rate', 'mcp_call_diversity']
  return names.map(name => {
    const entry = m[name]
    return {
      name,
      current: entry?.current ?? null,
      target: entry?.target ?? 0.9,
      status: mapStatus(entry?.status ?? 'warning'),
      unit: '%',
      sparkline: entry?.sparkline ?? [],
    }
  })
}

// =============================================================================
// Component
// =============================================================================

export function SloTab() {
  const t = useTranslations('governance')

  const [sloData, setSloData] = useState<SloApiResponse | null>(null)
  const [summaryData, setSummaryData] = useState<SummaryApiResponse | null>(null)
  const [sloLoading, setSloLoading] = useState(true)
  const [summaryLoading, setSummaryLoading] = useState(true)
  const [sloError, setSloError] = useState(false)
  const [summaryError, setSummaryError] = useState(false)

  // Fetch SLO
  useEffect(() => {
    let cancelled = false
    setSloLoading(true)
    fetch(`${API_BASE}/api/v1/ai/slo`)
      .then(r => r.ok ? r.json() : Promise.reject(r.status))
      .then(d => { if (!cancelled) { setSloData(d); setSloError(false) } })
      .catch(() => { if (!cancelled) setSloError(true) })
      .finally(() => { if (!cancelled) setSloLoading(false) })
    return () => { cancelled = true }
  }, [])

  // Fetch 30d summary
  useEffect(() => {
    let cancelled = false
    setSummaryLoading(true)
    fetch(`${API_BASE}/api/v1/ai/governance/summary?days=30`)
      .then(r => r.ok ? r.json() : Promise.reject(r.status))
      .then(d => { if (!cancelled) { setSummaryData(d); setSummaryError(false) } })
      .catch(() => { if (!cancelled) setSummaryError(true) })
      .finally(() => { if (!cancelled) setSummaryLoading(false) })
    return () => { cancelled = true }
  }, [])

  const metrics = sloData ? buildMetrics(sloData) : []
  const compliance = sloData?.overall_compliance ?? null

  const chartData: ViolationDataPoint[] = summaryData?.data ?? []
  const eventTypes: string[] = summaryData?.event_types ?? []

  return (
    <div style={{ padding: '20px', display: 'flex', flexDirection: 'column', gap: 16 }}>

      {/* SLO Error banner */}
      {sloError && (
        <GlassCard variant="subtle" padding="sm">
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <AlertTriangle size={14} style={{ color: '#F59E0B', flexShrink: 0 }} />
            <span style={{ fontFamily: "'DM Mono', monospace", fontSize: 11, color: '#87867f' }}>
              {t('slo.kpi.error')}
            </span>
          </div>
        </GlassCard>
      )}

      {/* Overall compliance — inline badge row */}
      {!sloLoading && compliance !== null && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            padding: '5px 10px',
            borderRadius: 6,
            background: compliance >= 0.95 ? 'rgba(34,197,94,0.08)' : 'rgba(245,158,11,0.08)',
            border: `0.5px solid ${compliance >= 0.95 ? '#22C55E40' : '#F59E0B40'}`,
          }}>
            <ShieldCheck size={13} style={{ color: compliance >= 0.95 ? '#22C55E' : '#F59E0B' }} />
            <span style={{
              fontFamily: 'Syne, sans-serif',
              fontSize: 13,
              fontWeight: 700,
              color: compliance >= 0.95 ? '#22C55E' : '#F59E0B',
            }}>
              {(compliance * 100).toFixed(1)}%
            </span>
            <span style={{ fontFamily: "'DM Mono', monospace", fontSize: 10, color: '#87867f' }}>
              {t('slo.compliance.title')}
            </span>
          </div>
          <span style={{ fontFamily: "'DM Mono', monospace", fontSize: 10, color: '#b8b4aa' }}>
            {t('slo.compliance.target')}
          </span>
        </div>
      )}

      {/* KPI cards — horizontal on desktop, stacked on mobile */}
      <div style={{
        display: 'flex',
        flexWrap: 'wrap',
        gap: 12,
      }}
      className="slo-kpi-grid"
      >
        {sloLoading
          ? [0, 1, 2].map(i => <SloKpiCard key={i} metric={{ name: 'decision_accuracy', current: null, target: 0.9, status: 'warning' }} loading />)
          : metrics.map(m => <SloKpiCard key={m.name} metric={m} />)
        }
      </div>

      {/* Violation timeline chart */}
      <SloViolationChart
        data={chartData}
        eventTypes={eventTypes}
        loading={summaryLoading}
        error={summaryError}
      />

      {/* Responsive helpers */}
      <style>{`
        .slo-kpi-grid > * { flex: 1; min-width: 200px; }
        @media (max-width: 640px) {
          .slo-kpi-grid > * { flex: 0 0 100%; min-width: 0; }
        }
      `}</style>
    </div>
  )
}
