'use client'

/**
 * FlywheelKPICard — ADR-073-C C2 + C3
 *
 * 飛輪健康度 KPI 面板。
 * C2: 初始載入 GET /api/v1/stats/summary（HTTP fallback）
 * C3: WebSocket /api/v1/stats/flywheel/ws 即時推送（旗標開啟時）
 *
 * 2026-04-12 ogt (ADR-073-C C2 + C3)
 */

import { useEffect, useRef, useState } from 'react'
import { FlywheelDiagram, type FlowItem } from './flywheel-diagram'

const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? ''
// ws(s):// mirror of NEXT_PUBLIC_API_URL
const WS_BASE = API_BASE.replace(/^https/, 'wss').replace(/^http/, 'ws')
const ENABLE_FLYWHEEL_WS = process.env.NEXT_PUBLIC_ENABLE_FLYWHEEL_WS === 'true'

interface FlywheelSummary {
  playbook_count: number
  // 2026-05-02 ogt + Claude Opus 4.7 — 後端 Bug 2 修復連動：
  // 樣本不足（< FLYWHEEL_MIN_SAMPLE）時後端回 null，line 122 的 != null guard 已正確處理
  execution_success_rate: number | null
  today_processed: number
  flywheel_conversions_today: number
  km_vectorized_rate: number
  km_unvectorized_count: number
  alertname_null_rate: number
  incidents_stuck: number
  computed_at: string
}

export function FlywheelKPICard() {
  const [data, setData] = useState<FlywheelSummary | null>(null)
  const [flowData, setFlowData] = useState<{ current_flow: FlowItem[]; nodes: Record<string, { status: string }>; type4_count?: number } | null>(null)
  const [error, setError] = useState(false)
  const wsRef = useRef<WebSocket | null>(null)

  // C2: HTTP fallback (initial load + 30s poll)
  useEffect(() => {
    let cancelled = false
    let pollId: ReturnType<typeof setInterval> | null = null

    const loadSummary = () => {
      fetch(`${API_BASE}/api/v1/stats/summary`)
        .then(r => r.ok ? r.json() : Promise.reject(r.status))
        .then(d => { if (!cancelled) { setData(d); setError(false) } })
        .catch(() => { if (!cancelled) setError(true) })
    }

    const loadFlow = () => {
      fetch(`${API_BASE}/api/v1/stats/flywheel`)
        .then(r => r.ok ? r.json() : null)
        .then(d => { if (!cancelled && d) setFlowData(d) })
        .catch(() => {})
    }

    const load = () => {
      loadSummary()
      loadFlow()
    }

    load()

    // C3: WebSocket — upgrades from polling when available, with reconnect (ADR-073-C C3)
    // 指數退避重連：1s → 2s → 4s → 8s → 最大 30s
    let wsRetryDelay = 1000
    let wsRetryTimer: ReturnType<typeof setTimeout> | null = null

    const connectWS = () => {
      if (!ENABLE_FLYWHEEL_WS || !WS_BASE || cancelled) return
      const ws = new WebSocket(`${WS_BASE}/api/v1/stats/flywheel/ws`)
      wsRef.current = ws

      ws.onopen = () => {
        wsRetryDelay = 1000  // 連線成功 — 重置退避
        if (pollId) { clearInterval(pollId); pollId = null }
      }
      ws.onmessage = (e) => {
        try {
          const msg = JSON.parse(e.data)
          if (msg.type === 'flywheel_summary' && !cancelled) {
            setData(msg.data)
            setError(false)
          }
        } catch { /* ignore malformed */ }
      }
      ws.onclose = () => {
        if (cancelled) return
        // 退回 HTTP polling
        if (!pollId) pollId = setInterval(load, 30_000)
        // 指數退避重連
        wsRetryTimer = setTimeout(() => {
          wsRetryDelay = Math.min(wsRetryDelay * 2, 30_000)
          connectWS()
        }, wsRetryDelay)
      }
      ws.onerror = () => ws.close()
    }

    connectWS()
    // Production default: HTTP polling stays authoritative unless WS is enabled explicitly.
    pollId = setInterval(load, 30_000)

    return () => {
      cancelled = true
      if (pollId) clearInterval(pollId)
      if (wsRetryTimer) clearTimeout(wsRetryTimer)
      wsRef.current?.close()
    }
  }, [])

  const fmt = (n: number | null | undefined, digits = 0) =>
    n == null ? '--' : n.toLocaleString(undefined, { maximumFractionDigits: digits })

  const pct = (n: number | null | undefined) =>
    n == null ? '--' : `${Math.round(n * 100)}%`

  const kpis = [
    {
      label: 'Playbooks',
      value: fmt(data?.playbook_count),
      color: data?.playbook_count != null && data.playbook_count >= 20 ? '#22C55E' : '#d97757',
      hint: '目標 ≥ 20',
    },
    {
      label: '修復成功率',
      value: pct(data?.execution_success_rate),
      color: data?.execution_success_rate != null && data.execution_success_rate >= 0.3 ? '#22C55E' : '#F59E0B',
      hint: '目標 ≥ 30%',
    },
    {
      label: '今日轉化',
      value: fmt(data?.flywheel_conversions_today),
      color: '#4A90D9',
      hint: '今日新增 KM',
    },
    {
      label: 'KM 向量化率',
      value: pct(data?.km_vectorized_rate),
      color: data?.km_vectorized_rate != null && data.km_vectorized_rate >= 0.95 ? '#22C55E' : '#F59E0B',
      hint: '目標 ≥ 95%',
    },
  ]

  return (
    <div style={{
      background: '#fff',
      border: '0.5px solid #e0ddd4',
      borderRadius: 12,
      overflow: 'hidden',
      boxShadow: '0 1px 4px rgba(0,0,0,0.05)',
      flexShrink: 0,
    }}>
      {/* Header */}
      <div style={{
        padding: '10px 14px',
        borderBottom: '0.5px solid #e0ddd4',
        fontSize: 14, fontWeight: 700, color: '#141413',
        letterSpacing: '0.5px',
        fontFamily: 'var(--font-body), monospace', background: '#faf9f3',
        display: 'flex', alignItems: 'center', gap: 8,
      }}>
        <div style={{ width: 6, height: 6, borderRadius: '50%', background: '#22C55E', flexShrink: 0 }} />
        飛輪健康度
        {error && (
          <span style={{ marginLeft: 'auto', fontSize: 10, color: '#d97757' }}>API 離線</span>
        )}
        {data && !error && (
          <span style={{ marginLeft: 'auto', fontSize: 10, color: '#87867f' }}>
            {new Date(data.computed_at).toLocaleTimeString('zh-TW', { hour: '2-digit', minute: '2-digit' })}
          </span>
        )}
      </div>

      {/* KPI Grid */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 1, background: '#e0ddd4' }}>
        {kpis.map(({ label, value, color, hint }) => (
          <div key={label} style={{ background: '#fff', padding: '10px 14px' }}>
            <div style={{ fontSize: 10, color: '#87867f', fontWeight: 500, textTransform: 'uppercase', letterSpacing: '0.5px' }}>
              {label}
            </div>
            <div style={{ fontSize: 20, fontWeight: 700, color, marginTop: 2 }}>{value}</div>
            <div style={{ fontSize: 9, color: '#87867f', marginTop: 1 }}>{hint}</div>
          </div>
        ))}
      </div>

      {/* C4: 飛輪節點圖 + 人工介入路徑 */}
      <div style={{ padding: '10px 14px', borderTop: '0.5px solid #e0ddd4' }}>
        <FlywheelDiagram
          currentFlow={flowData?.current_flow ?? []}
          activeNodes={flowData?.nodes ?? {}}
          type4Count={flowData?.type4_count ?? 0}
        />
      </div>

      {/* Stuck incidents warning */}
      {data?.incidents_stuck != null && data.incidents_stuck > 0 && (
        <div style={{
          padding: '6px 14px',
          background: 'rgba(217,119,87,0.06)',
          borderTop: '0.5px solid #e0ddd4',
          fontSize: 11, color: '#a04010',
        }}>
          {data.incidents_stuck} 筆 Incident 卡在 INVESTIGATING {'>'} 24h
        </div>
      )}
    </div>
  )
}
