import { useEffect, useState } from 'react'
import { guardiaApi } from '../api/clients'

type Tab = 'insights' | 'learning' | 'predict' | 'benchmark'

export default function AiPlatform() {
  const [tab, setTab] = useState<Tab>('insights')
  const tabs: { id: Tab; label: string; icon: string }[] = [
    { id: 'insights', label: 'AI 인사이트', icon: '🧠' },
    { id: 'learning', label: 'Learning Loop', icon: '🔄' },
    { id: 'predict', label: '예측 분석', icon: '🔮' },
    { id: 'benchmark', label: '벤치마킹', icon: '📊' },
  ]
  return (
    <div style={{ padding: '24px 28px' }}>
      <h2 style={{ margin: '0 0 20px', fontSize: 20, fontWeight: 700 }}>🧠 AI 플랫폼</h2>
      <div style={{ display: 'flex', gap: 4, marginBottom: 20, borderBottom: '1px solid #e2e8f0' }}>
        {tabs.map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            padding: '8px 16px', border: 'none', background: 'none', cursor: 'pointer',
            fontSize: 13, fontWeight: tab === t.id ? 700 : 400,
            color: tab === t.id ? '#003366' : '#64748b',
            borderBottom: tab === t.id ? '2px solid #003366' : '2px solid transparent',
          }}>{t.icon} {t.label}</button>
        ))}
      </div>
      {tab === 'insights' && <InsightsTab />}
      {tab === 'learning' && <LearningTab />}
      {tab === 'predict' && <PredictTab />}
      {tab === 'benchmark' && <BenchmarkTab />}
    </div>
  )
}

function Card({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div style={{ background: '#fff', border: '1px solid #e2e8f0', borderRadius: 10, padding: 20, marginBottom: 16 }}>
      <h3 style={{ fontSize: 14, fontWeight: 600, margin: '0 0 14px' }}>{title}</h3>
      {children}
    </div>
  )
}

function InsightsTab() {
  const [weekly, setWeekly] = useState<any>(null)
  const [anomalies, setAnomalies] = useState<any>(null)
  useEffect(() => {
    guardiaApi.get('/api/insights/weekly').then((r: any) => setWeekly(r.data)).catch(() => {})
    guardiaApi.get('/api/insights/anomalies').then((r: any) => setAnomalies(r.data)).catch(() => {})
  }, [])
  return (
    <>
      {anomalies?.anomalies?.length > 0 && (
        <div style={{ background: '#fef2f2', border: '1px solid #fecaca', borderRadius: 8, padding: 12, marginBottom: 16 }}>
          <strong style={{ fontSize: 13 }}>⚠️ 이상 감지 ({anomalies.anomalies.length}건)</strong>
          {anomalies.anomalies.map((a: any, i: number) => (
            <div key={i} style={{ fontSize: 12, marginTop: 6, color: '#7f1d1d' }}>{a.message}</div>
          ))}
        </div>
      )}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 12, marginBottom: 16 }}>
        {weekly && [
          { label: '신규 SR', val: weekly.stats?.total || 0, color: '#003366' },
          { label: '완료율', val: `${weekly.stats?.completion_rate || 0}%`, color: '#10B981' },
          { label: '미처리', val: weekly.stats?.open || 0, color: '#EF4444' },
        ].map(s => (
          <div key={s.label} style={{ background: '#fff', border: `1px solid #e2e8f0`, borderLeft: `4px solid ${s.color}`, borderRadius: 8, padding: 16 }}>
            <div style={{ fontSize: 28, fontWeight: 700, color: s.color }}>{s.val}</div>
            <div style={{ fontSize: 11, color: '#64748b' }}>{s.label}</div>
          </div>
        ))}
      </div>
      <Card title="🤖 AI 주간 인사이트">
        <p style={{ fontSize: 13, lineHeight: 1.8, whiteSpace: 'pre-wrap', color: '#374151' }}>
          {weekly?.ai_insight || '데이터 수집 중...'}
        </p>
      </Card>
    </>
  )
}

function LearningTab() {
  const [status, setStatus] = useState<any>(null)
  const [quality, setQuality] = useState<any>(null)
  const [history, setHistory] = useState<any[]>([])
  useEffect(() => {
    guardiaApi.get('/api/learn/status').then((r: any) => setStatus(r.data)).catch(() => {})
    guardiaApi.get('/api/learn/quality').then((r: any) => setQuality(r.data)).catch(() => {})
    guardiaApi.get('/api/learn/history?limit=10').then((r: any) => setHistory(r.data || [])).catch(() => {})
  }, [])
  async function startTrain() {
    await guardiaApi.post('/api/learn/train')
    guardiaApi.get('/api/learn/history?limit=10').then((r: any) => setHistory(r.data || [])).catch(() => {})
  }
  return (
    <>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        <Card title="📦 학습 데이터">
          <div style={{ fontSize: 36, fontWeight: 700, color: '#003366' }}>{status?.available_samples || 0}</div>
          <div style={{ fontSize: 12, color: '#64748b' }}>수집 가능 샘플</div>
          <div style={{ fontSize: 12, marginTop: 6 }}>
            RAG 피드백: {status?.high_quality_rag || 0} · SR 이력: {status?.sr_samples || 0}
          </div>
          <button onClick={startTrain} disabled={!status?.ready_to_train} style={{
            marginTop: 12, padding: '7px 16px', background: status?.ready_to_train ? '#003366' : '#94a3b8',
            color: '#fff', border: 'none', borderRadius: 6, cursor: status?.ready_to_train ? 'pointer' : 'not-allowed', fontSize: 12,
          }}>🚀 파인튜닝 시작</button>
        </Card>
        <Card title="📈 모델 품질">
          <div style={{ fontSize: 48, fontWeight: 700, color: '#003366', textAlign: 'center' }}>{quality?.quality_grade || 'N/A'}</div>
          <div style={{ textAlign: 'center', fontSize: 12, color: '#64748b' }}>
            평균 {quality?.avg_rating || 0}점 · 긍정 {quality?.positive_rate || 0}%
          </div>
        </Card>
      </div>
      <Card title="📋 학습 이력">
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
          <thead><tr style={{ borderBottom: '1px solid #f1f5f9' }}>
            {['모델', '상태', '샘플', '시작'].map(h => <th key={h} style={{ textAlign: 'left', padding: '6px 8px', color: '#64748b', fontSize: 11 }}>{h}</th>)}
          </tr></thead>
          <tbody>
            {history.slice(0, 8).map((h: any) => (
              <tr key={h.id} style={{ borderBottom: '1px solid #f8fafc' }}>
                <td style={{ padding: '8px', fontFamily: 'monospace', fontSize: 11 }}>{h.model_name || '-'}</td>
                <td style={{ padding: '8px', color: h.status === 'SUCCESS' ? '#10B981' : h.status === 'FAILED' ? '#EF4444' : '#F59E0B' }}>{h.status}</td>
                <td style={{ padding: '8px' }}>{h.samples_used || 0}</td>
                <td style={{ padding: '8px', color: '#94a3b8', fontSize: 11 }}>{h.started_at ? new Date(h.started_at).toLocaleDateString('ko-KR') : '-'}</td>
              </tr>
            ))}
            {!history.length && <tr><td colSpan={4} style={{ textAlign: 'center', padding: 16, color: '#94a3b8' }}>이력 없음</td></tr>}
          </tbody>
        </table>
      </Card>
    </>
  )
}

function PredictTab() {
  const [sla, setSla] = useState<any>(null)
  const [surge, setSurge] = useState<any>(null)
  useEffect(() => {
    guardiaApi.get('/api/predict/sla-breach').then((r: any) => setSla(r.data)).catch(() => {})
    guardiaApi.get('/api/predict/sr-surge').then((r: any) => setSurge(r.data)).catch(() => {})
  }, [])
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
      <Card title="📉 SLA 위반 예측 (7일)">
        <div style={{ fontSize: 36, fontWeight: 700, color: sla?.status === 'CRITICAL' ? '#EF4444' : sla?.status === 'WARNING' ? '#F59E0B' : '#10B981' }}>
          {Math.round((sla?.breach_probability_7d || 0) * 100)}%
        </div>
        <div style={{ fontSize: 12, color: '#64748b' }}>현재 SLA: {sla?.current_rate || 0}% · 목표: {sla?.target || 95}%</div>
        {sla?.insight && <p style={{ fontSize: 12, lineHeight: 1.7, marginTop: 10, color: '#374151' }}>{sla.insight}</p>}
      </Card>
      <Card title="📈 SR 급증 감지">
        <div style={{ fontSize: 36, fontWeight: 700, color: surge?.status === 'SURGE' ? '#EF4444' : surge?.status === 'HIGH' ? '#F59E0B' : '#10B981' }}>
          {surge?.surge_ratio || 1}x
        </div>
        <div style={{ fontSize: 12, color: '#64748b' }}>오늘 {surge?.today_count || 0}건 · 7일 평균 {surge?.avg_7d || 0}건</div>
        {surge?.insight && <p style={{ fontSize: 12, lineHeight: 1.7, marginTop: 10, color: '#374151' }}>{surge.insight}</p>}
      </Card>
    </div>
  )
}

function BenchmarkTab() {
  const [comp, setComp] = useState<any>(null)
  const [rank, setRank] = useState<any>(null)
  useEffect(() => {
    guardiaApi.get('/api/benchmark/comparison').then((r: any) => setComp(r.data)).catch(() => {})
    guardiaApi.get('/api/benchmark/my-rank').then((r: any) => setRank(r.data)).catch(() => {})
  }, [])
  async function contribute() { await guardiaApi.post('/api/benchmark/contribute') }
  return (
    <>
      <Card title="📊 업계 평균 대비 비교">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 16 }}>
          {(comp?.comparison || []).map((m: any) => (
            <div key={m.metric} style={{ textAlign: 'center', padding: 16, background: '#f8fafc', borderRadius: 8 }}>
              <div style={{ fontSize: 11, color: '#64748b', marginBottom: 6 }}>{m.metric}</div>
              <div style={{ fontSize: 28, fontWeight: 700, color: m.status === 'ABOVE' ? '#10B981' : '#EF4444' }}>
                {m.mine}<span style={{ fontSize: 12 }}>{m.unit}</span>
              </div>
              <div style={{ fontSize: 11, marginTop: 4 }}>업계 평균: {m.industry}{m.unit}</div>
              <div style={{ fontSize: 11, color: m.status === 'ABOVE' ? '#10B981' : '#EF4444', marginTop: 2 }}>
                {m.status === 'ABOVE' ? '▲ 평균 이상' : '▼ 평균 이하'}
              </div>
            </div>
          ))}
        </div>
      </Card>
      <div style={{ marginTop: 12 }}>
        <button onClick={contribute} style={{ padding: '7px 16px', border: '1px solid #e2e8f0', borderRadius: 6, cursor: 'pointer', fontSize: 12 }}>
          📤 익명 데이터 기여
        </button>
        <span style={{ fontSize: 11, color: '#94a3b8', marginLeft: 8 }}>기여 시 더 정확한 벤치마킹 가능 (완전 익명화)</span>
      </div>
    </>
  )
}
