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

interface CsapSite {
  inst_id: number; scan_id: string; compliance_rate: number
  grade: string; pass_count: number; total: number
  scanned_at: string | null
}
interface CsapItem {
  id: string; cat: string; sev: string; auto: boolean; name: string
}
interface ScanResult {
  scan_id: string; inst_id: number
  total_items: number; pass: number; fail: number
  partial: number; manual_required: number
  compliance_rate: number; grade: string
  critical_findings: string[]
}

const GRADE_COLOR: Record<string, string> = {
  A: '#22c55e', B: '#4f6ef7', C: '#f59e0b', D: '#ef4444',
}
const SEV_COLOR: Record<string, string> = {
  HIGH: '#ef4444', MEDIUM: '#f59e0b', LOW: '#22c55e',
}

export default function CsapConsole() {
  const [sites,    setSites]    = useState<CsapSite[]>([])
  const [items,    setItems]    = useState<CsapItem[]>([])
  const [selected, setSelected] = useState<CsapSite | null>(null)
  const [scanning, setScanning] = useState<number | null>(null)
  const [loading,  setLoading]  = useState(true)
  const [msg,      setMsg]      = useState('')

  const load = () => {
    Promise.all([
      guardiaApi.get('/api/compliance/csap/dashboard'),
      guardiaApi.get('/api/compliance/csap/items'),
    ]).then(([d, i]) => {
      setSites(d.data.institutions ?? [])
      setItems(i.data.items ?? [])
    }).finally(() => setLoading(false))
  }

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

  const runScan = async (instId: number) => {
    if (!confirm(`기관 #${instId} CSAP 전체 점검을 실행하시겠습니까?`)) return
    setScanning(instId); setMsg('')
    try {
      const r = await guardiaApi.post('/api/compliance/csap/scan', { inst_id: instId })
      const res: ScanResult = r.data
      setMsg(`✔ 점검 완료 — 준수율 ${res.compliance_rate}% (${res.grade}등급)`)
      load()
    } catch (e: any) {
      setMsg(`✘ 점검 실패: ${e.response?.data?.detail ?? e.message}`)
    } finally { setScanning(null) }
  }

  const downloadExcel = (scanId: string) => {
    guardiaApi.get(`/api/compliance/csap/report/excel?scan_id=${scanId}`,
      { responseType: 'blob' }
    ).then(r => {
      const url = URL.createObjectURL(r.data)
      const a = document.createElement('a')
      a.href = url; a.download = `CSAP_${scanId}.xlsx`; a.click()
      URL.revokeObjectURL(url)
    })
  }

  const catSummary = items.reduce<Record<string, { total: number; auto: number }>>(
    (acc, i) => {
      if (!acc[i.cat]) acc[i.cat] = { total: 0, auto: 0 }
      acc[i.cat].total++
      if (i.auto) acc[i.cat].auto++
      return acc
    }, {}
  )

  if (loading) return <div style={{ color: '#94a3b8', padding: 40 }}>로딩 중...</div>

  return (
    <div>
      {/* 점검 항목 요약 */}
      <div style={{ display: 'flex', gap: 16, marginBottom: 24 }}>
        {Object.entries(catSummary).map(([cat, s]) => (
          <div key={cat} style={{ background: '#fff', border: '1px solid #e2e8f0',
            borderRadius: 10, padding: '14px 20px', flex: 1 }}>
            <div style={{ fontSize: 12, color: '#64748b' }}>{cat} 보안</div>
            <div style={{ fontSize: 22, fontWeight: 700, color: '#1e293b', marginTop: 4 }}>
              {s.total}개
            </div>
            <div style={{ fontSize: 11, color: '#94a3b8', marginTop: 2 }}>
              자동 {s.auto}개 / 수동 {s.total - s.auto}개
            </div>
          </div>
        ))}
        <div style={{ background: '#fff', border: '1px solid #e2e8f0',
          borderRadius: 10, padding: '14px 20px', flex: 1 }}>
          <div style={{ fontSize: 12, color: '#64748b' }}>전체 항목</div>
          <div style={{ fontSize: 22, fontWeight: 700, color: '#1e293b', marginTop: 4 }}>
            {items.length}개
          </div>
          <div style={{ fontSize: 11, color: '#94a3b8', marginTop: 2 }}>
            자동 {items.filter(i => i.auto).length}개 / 수동 {items.filter(i => !i.auto).length}개
          </div>
        </div>
      </div>

      {msg && (
        <div style={{ padding: '10px 16px', borderRadius: 8, marginBottom: 16,
          background: msg.startsWith('✔') ? '#f0fdf4' : '#fef2f2',
          color: msg.startsWith('✔') ? '#16a34a' : '#dc2626',
          border: `1px solid ${msg.startsWith('✔') ? '#bbf7d0' : '#fecaca'}`,
          fontSize: 13 }}>
          {msg}
        </div>
      )}

      {/* 기관별 준수율 테이블 */}
      <div style={{ background: '#fff', border: '1px solid #e2e8f0', borderRadius: 10,
        overflow: 'hidden', marginBottom: 20 }}>
        <div style={{ padding: '14px 20px', borderBottom: '1px solid #f1f5f9',
          fontWeight: 600, fontSize: 13, color: '#1e293b' }}>
          기관별 CSAP 준수율
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
          <thead>
            <tr style={{ background: '#f8fafc' }}>
              {['기관 ID','준수율','등급','통과/전체','마지막 점검','액션'].map(h => (
                <th key={h} style={{ padding: '10px 14px', textAlign: 'left',
                  fontWeight: 600, color: '#475569', fontSize: 12,
                  borderBottom: '1px solid #e2e8f0' }}>{h}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {sites.map(s => (
              <tr key={s.inst_id}
                style={{ borderBottom: '1px solid #f1f5f9',
                  background: selected?.inst_id === s.inst_id ? '#f8fafc' : undefined,
                  cursor: 'pointer' }}
                onClick={() => setSelected(selected?.inst_id === s.inst_id ? null : s)}>
                <td style={{ padding: '10px 14px', color: '#64748b' }}>기관 #{s.inst_id}</td>
                <td style={{ padding: '10px 14px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <div style={{ flex: 1, maxWidth: 120, height: 6, background: '#f1f5f9',
                      borderRadius: 3, overflow: 'hidden' }}>
                      <div style={{ width: `${s.compliance_rate}%`, height: '100%',
                        background: GRADE_COLOR[s.grade] ?? '#4f6ef7', borderRadius: 3 }} />
                    </div>
                    <span style={{ fontWeight: 700, color: GRADE_COLOR[s.grade] ?? '#1e293b',
                      minWidth: 40 }}>
                      {s.compliance_rate}%
                    </span>
                  </div>
                </td>
                <td style={{ padding: '10px 14px' }}>
                  <span style={{ padding: '3px 12px', borderRadius: 12, fontSize: 12,
                    fontWeight: 700, color: '#fff',
                    background: GRADE_COLOR[s.grade] ?? '#94a3b8' }}>
                    {s.grade}등급
                  </span>
                </td>
                <td style={{ padding: '10px 14px', color: '#475569' }}>
                  {s.pass_count}/{s.total}
                </td>
                <td style={{ padding: '10px 14px', color: '#64748b', fontSize: 12 }}>
                  {s.scanned_at ? new Date(s.scanned_at).toLocaleDateString('ko-KR') : '미점검'}
                </td>
                <td style={{ padding: '10px 14px' }}>
                  <div style={{ display: 'flex', gap: 6 }} onClick={e => e.stopPropagation()}>
                    <button onClick={() => runScan(s.inst_id)}
                      disabled={scanning === s.inst_id}
                      style={{ padding: '4px 10px', fontSize: 11, borderRadius: 6,
                        background: scanning === s.inst_id ? '#e2e8f0' : '#4f6ef7',
                        color: scanning === s.inst_id ? '#94a3b8' : '#fff',
                        border: 'none', cursor: scanning === s.inst_id ? 'not-allowed' : 'pointer' }}>
                      {scanning === s.inst_id ? '점검 중..' : '점검'}
                    </button>
                    {s.scan_id && (
                      <button onClick={() => downloadExcel(s.scan_id)}
                        style={{ padding: '4px 10px', fontSize: 11, borderRadius: 6,
                          background: '#f1f5f9', color: '#475569',
                          border: '1px solid #e2e8f0', cursor: 'pointer' }}>
                        Excel
                      </button>
                    )}
                  </div>
                </td>
              </tr>
            ))}
            {sites.length === 0 && (
              <tr><td colSpan={6} style={{ padding: 40, textAlign: 'center', color: '#94a3b8' }}>
                점검 이력이 없습니다. 기관을 선택해 점검을 실행하세요.
              </td></tr>
            )}
          </tbody>
        </table>
      </div>

      {/* 점검 항목 목록 */}
      <div style={{ background: '#fff', border: '1px solid #e2e8f0', borderRadius: 10,
        overflow: 'hidden' }}>
        <div style={{ padding: '14px 20px', borderBottom: '1px solid #f1f5f9',
          fontWeight: 600, fontSize: 13, color: '#1e293b' }}>
          CSAP 점검 항목 목록 ({items.length}개)
        </div>
        <div style={{ maxHeight: 300, overflowY: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
            <thead>
              <tr style={{ background: '#f8fafc', position: 'sticky', top: 0 }}>
                {['항목ID','카테고리','항목명','심각도','점검방식'].map(h => (
                  <th key={h} style={{ padding: '8px 14px', textAlign: 'left',
                    fontWeight: 600, color: '#475569',
                    borderBottom: '1px solid #e2e8f0' }}>{h}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {items.map(i => (
                <tr key={i.id} style={{ borderBottom: '1px solid #f8fafc' }}>
                  <td style={{ padding: '7px 14px', fontWeight: 700, color: '#4f6ef7' }}>{i.id}</td>
                  <td style={{ padding: '7px 14px', color: '#64748b' }}>{i.cat}</td>
                  <td style={{ padding: '7px 14px', color: '#1e293b' }}>{i.name}</td>
                  <td style={{ padding: '7px 14px' }}>
                    <span style={{ padding: '2px 8px', borderRadius: 10, fontSize: 10,
                      fontWeight: 700, color: '#fff',
                      background: SEV_COLOR[i.sev] ?? '#94a3b8' }}>
                      {i.sev}
                    </span>
                  </td>
                  <td style={{ padding: '7px 14px' }}>
                    <span style={{ fontSize: 11, color: i.auto ? '#22c55e' : '#f59e0b',
                      fontWeight: 600 }}>
                      {i.auto ? '⚡ 자동' : '📋 수동'}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  )
}
