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

const STATUS_COLOR: Record<string, string> = {
  GREEN: '#22c55e', YELLOW: '#f59e0b', RED: '#ef4444', NO_DATA: '#94a3b8',
}
const STATUS_ICON: Record<string, string> = {
  GREEN: '✅', YELLOW: '⚠️', RED: '❌', NO_DATA: '❔',
}

interface KPI {
  id: number; name: string; display_name: string
  unit: string; direction: string; target: number
  current_value: number | null; status: string
  achievement_pct: number | null; last_calculated_at: string | null
}

interface Dashboard { kpis: KPI[]; summary: Record<string, number>; overall_status: string }

function GaugeBar({ pct }: { pct: number | null }) {
  const p = Math.min(100, Math.max(0, pct ?? 0))
  const color = p >= 95 ? '#22c55e' : p >= 80 ? '#f59e0b' : '#ef4444'
  return (
    <div style={{ background: '#f1f5f9', borderRadius: 4, height: 6, marginTop: 6 }}>
      <div style={{ width: `${p}%`, height: 6, background: color, borderRadius: 4, transition: 'width .4s' }} />
    </div>
  )
}

export default function KpiDashboard() {
  const [data, setData] = useState<Dashboard | null>(null)
  const [loading, setLoading] = useState(true)

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

  async function load() {
    setLoading(true)
    try {
      const d = await guardiaApi.get('/api/kpi/dashboard').then((r: any) => r.data)
      setData(d)
    } catch { /* 오류 무시 */ }
    setLoading(false)
  }

  async function applyTemplates() {
    await guardiaApi.post('/api/kpi/apply-template', {
      template_names: ['MTTR', 'FCR', 'SLA_COMPLIANCE', 'SR_BACKLOG', 'DEPLOY_SUCCESS_RATE'],
    })
    load()
  }

  async function recalc(id: number) {
    await guardiaApi.post(`/api/kpi/${id}/calculate`)
    load()
  }

  if (loading) return <div style={{ padding: 32, textAlign: 'center' }}>⏳ 로딩 중...</div>

  const overall = data?.overall_status || 'NO_DATA'
  const summary = data?.summary || {}

  return (
    <div style={{ padding: '24px 28px' }}>
      {/* 헤더 */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
        <div>
          <h2 style={{ margin: 0, fontSize: 20, fontWeight: 700 }}>
            {STATUS_ICON[overall]} KPI 대시보드
          </h2>
          <p style={{ margin: '4px 0 0', color: '#64748b', fontSize: 13 }}>
            GREEN:{summary.GREEN||0} · YELLOW:{summary.YELLOW||0} · RED:{summary.RED||0}
          </p>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button onClick={load} style={{ padding: '6px 14px', border: '1px solid #e2e8f0', borderRadius: 6, background: '#fff', cursor: 'pointer' }}>
            🔄 새로고침
          </button>
          {(!data?.kpis.length) && (
            <button onClick={applyTemplates} style={{ padding: '6px 14px', background: '#003366', color: '#fff', border: 'none', borderRadius: 6, cursor: 'pointer' }}>
              📋 템플릿 적용
            </button>
          )}
        </div>
      </div>

      {/* KPI 카드 그리드 */}
      {data?.kpis.length === 0 ? (
        <div style={{ padding: 48, textAlign: 'center', border: '2px dashed #e2e8f0', borderRadius: 12 }}>
          <p style={{ color: '#94a3b8' }}>KPI가 없습니다.</p>
          <button onClick={applyTemplates} style={{ padding: '8px 20px', background: '#003366', color: '#fff', border: 'none', borderRadius: 8, cursor: 'pointer' }}>
            내장 KPI 5개 등록
          </button>
        </div>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))', gap: 16 }}>
          {data?.kpis.map(k => (
            <div key={k.id} style={{ background: '#fff', border: `1px solid #e2e8f0`, borderLeft: `4px solid ${STATUS_COLOR[k.status]}`, borderRadius: 10, padding: 18 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
                <span style={{ fontSize: 13, fontWeight: 600, color: '#1e293b' }}>{k.display_name}</span>
                <span style={{ fontSize: 11, background: STATUS_COLOR[k.status], color: '#fff', padding: '2px 8px', borderRadius: 10 }}>{k.status}</span>
              </div>
              <div style={{ fontSize: 30, fontWeight: 700, color: STATUS_COLOR[k.status] }}>
                {k.current_value !== null ? k.current_value : '—'}
                <span style={{ fontSize: 14, marginLeft: 4, color: '#64748b' }}>{k.unit}</span>
              </div>
              <div style={{ fontSize: 12, color: '#94a3b8', marginTop: 4 }}>
                목표: {k.target}{k.unit} · 달성: {k.achievement_pct !== null ? `${k.achievement_pct}%` : '—'}
              </div>
              <GaugeBar pct={k.achievement_pct} />
              <button onClick={() => recalc(k.id)} style={{ marginTop: 10, width: '100%', padding: '5px', border: '1px solid #e2e8f0', borderRadius: 6, background: '#f8fafc', cursor: 'pointer', fontSize: 12 }}>
                ↻ 재계산
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
