import { useEffect, useState } from 'react'
import {
  LineChart, Line, BarChart, Bar, PieChart, Pie, Cell,
  XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer,
} from 'recharts'
import { guardiaApi } from '../api/clients'

const COLORS = ['#003366', '#00A0C8', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6']

export default function BiAnalytics() {
  const [overview, setOverview] = useState<any>(null)
  const [srTrend, setSrTrend] = useState<any>(null)
  const [pie, setPie] = useState<any>(null)
  const [mttr, setMttr] = useState<any>(null)
  const [tab, setTab] = useState<'overview' | 'trend' | 'engineer' | 'mttr'>('overview')

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

  async function loadData() {
    const [o, t, p, m] = await Promise.all([
      guardiaApi.get('/api/bi/overview').then((r: any) => r.data).catch(() => null),
      guardiaApi.get('/api/bi/sr-trend?days=30').then((r: any) => r.data).catch(() => null),
      guardiaApi.get('/api/bi/category-pie?days=30').then((r: any) => r.data).catch(() => null),
      guardiaApi.get('/api/bi/mttr-trend?months=6').then((r: any) => r.data).catch(() => null),
    ])
    setOverview(o); setSrTrend(t); setPie(p); setMttr(m)
  }

  const tabs = [
    { id: 'overview', label: '개요' },
    { id: 'trend', label: 'SR 트렌드' },
    { id: 'engineer', label: '엔지니어' },
    { id: 'mttr', label: 'MTTR' },
  ] as const

  return (
    <div style={{ padding: '24px 28px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
        <h2 style={{ margin: 0, fontSize: 20, fontWeight: 700 }}>📊 BI 대시보드</h2>
        <button onClick={loadData} style={{ padding: '6px 14px', border: '1px solid #e2e8f0', borderRadius: 6, background: '#fff', cursor: 'pointer' }}>🔄</button>
      </div>

      {/* 탭 */}
      <div style={{ display: 'flex', gap: 4, marginBottom: 20, borderBottom: '1px solid #e2e8f0', paddingBottom: 0 }}>
        {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.label}</button>
        ))}
      </div>

      {/* 개요 탭 */}
      {tab === 'overview' && (
        <>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', gap: 12, marginBottom: 20 }}>
            {(overview?.cards || []).map((c: any) => (
              <div key={c.key} style={{ background: '#fff', border: '1px solid #e2e8f0', borderLeft: '4px solid #003366', borderRadius: 8, padding: 14 }}>
                <div style={{ fontSize: 24, fontWeight: 700 }}>{c.value}</div>
                <div style={{ fontSize: 11, color: '#64748b' }}>{c.label} ({c.unit})</div>
              </div>
            ))}
          </div>
          {pie && (
            <div style={{ background: '#fff', border: '1px solid #e2e8f0', borderRadius: 10, padding: 20 }}>
              <h3 style={{ fontSize: 14, fontWeight: 600, margin: '0 0 16px' }}>SR 카테고리 분포 (30일)</h3>
              <ResponsiveContainer width="100%" height={240}>
                <PieChart>
                  <Pie data={pie.data || []} dataKey="count" nameKey="category" cx="50%" cy="50%" outerRadius={90} label={({category, pct}) => `${category} ${pct}%`}>
                    {(pie.data || []).map((_: any, i: number) => <Cell key={i} fill={COLORS[i % COLORS.length]} />)}
                  </Pie>
                  <Tooltip />
                </PieChart>
              </ResponsiveContainer>
            </div>
          )}
        </>
      )}

      {/* SR 트렌드 탭 */}
      {tab === 'trend' && srTrend && (
        <div style={{ background: '#fff', border: '1px solid #e2e8f0', borderRadius: 10, padding: 20 }}>
          <h3 style={{ fontSize: 14, fontWeight: 600, margin: '0 0 16px' }}>SR 생성/완료 추이 (30일)</h3>
          <ResponsiveContainer width="100%" height={280}>
            <LineChart data={(srTrend.labels || []).map((d: string, i: number) => ({
              date: d.slice(5),
              신규: srTrend.datasets[0]?.data[i] || 0,
              완료: srTrend.datasets[1]?.data[i] || 0,
            }))}>
              <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
              <XAxis dataKey="date" tick={{ fontSize: 11 }} />
              <YAxis tick={{ fontSize: 11 }} />
              <Tooltip />
              <Legend />
              <Line type="monotone" dataKey="신규" stroke="#003366" strokeWidth={2} dot={false} />
              <Line type="monotone" dataKey="완료" stroke="#10B981" strokeWidth={2} dot={false} />
            </LineChart>
          </ResponsiveContainer>
        </div>
      )}

      {/* MTTR 탭 */}
      {tab === 'mttr' && mttr && (
        <div style={{ background: '#fff', border: '1px solid #e2e8f0', borderRadius: 10, padding: 20 }}>
          <h3 style={{ fontSize: 14, fontWeight: 600, margin: '0 0 16px' }}>MTTR 월별 추이 (시간)</h3>
          <ResponsiveContainer width="100%" height={280}>
            <BarChart data={(mttr.raw || []).map((r: any) => ({ month: r.month, mttr: r.mttr_hours }))}>
              <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
              <XAxis dataKey="month" tick={{ fontSize: 11 }} />
              <YAxis tick={{ fontSize: 11 }} />
              <Tooltip formatter={(v: any) => `${v}시간`} />
              <Bar dataKey="mttr" fill="#6366F1" radius={[4, 4, 0, 0]} />
            </BarChart>
          </ResponsiveContainer>
        </div>
      )}

      {tab === 'engineer' && <EngineerLoad />}
    </div>
  )
}

function EngineerLoad() {
  const [data, setData] = useState<any>(null)
  useEffect(() => {
    guardiaApi.get('/api/bi/engineer-load?days=30').then((r: any) => setData(r.data)).catch(() => {})
  }, [])
  if (!data) return <div style={{ padding: 32, textAlign: 'center' }}>⏳</div>
  const combined = (data.labels || []).map((name: string, i: number) => ({
    name, 완료: data.datasets[0]?.data[i] || 0, 진행중: data.datasets[1]?.data[i] || 0,
  }))
  return (
    <div style={{ background: '#fff', border: '1px solid #e2e8f0', borderRadius: 10, padding: 20 }}>
      <h3 style={{ fontSize: 14, fontWeight: 600, margin: '0 0 16px' }}>엔지니어별 SR 워크로드</h3>
      <ResponsiveContainer width="100%" height={280}>
        <BarChart data={combined} layout="vertical">
          <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
          <XAxis type="number" tick={{ fontSize: 11 }} />
          <YAxis type="category" dataKey="name" tick={{ fontSize: 11 }} width={90} />
          <Tooltip />
          <Legend />
          <Bar dataKey="완료" fill="#10B981" stackId="a" />
          <Bar dataKey="진행중" fill="#F59E0B" stackId="a" />
        </BarChart>
      </ResponsiveContainer>
    </div>
  )
}
