import { useEffect, useState } from 'react'
import { BarChart3, Factory, ScanSearch, Boxes, TrendingUp } from 'lucide-react'
import Chart from '../components/Chart'
import { Card, StatCard } from '../components/ui'
import {
  getProductionKpi, getQualityKpi, getInventoryKpi, getDailyProduction, getTopItems,
} from '../api/client'

function toChart(raw: any, name: string) {
  if (!raw) return undefined
  if (raw.labels && raw.series) return raw
  if (Array.isArray(raw)) return { labels: raw.map((r: any) => r.label || r.name || r.itemName || r.itemCode || r.date), series: [{ name, data: raw.map((r: any) => Number(r.value ?? r.qty ?? r.count ?? 0)) }] }
  const e = Object.entries(raw).filter(([, v]) => typeof v === 'number')
  return e.length ? { labels: e.map(x => x[0]), series: [{ name, data: e.map(x => x[1] as number) }] } : undefined
}
function num(o: any, ...keys: string[]) { for (const k of keys) if (o?.[k] != null) return Number(o[k]) || 0; return 0 }

export default function Analytics() {
  const [prod, setProd] = useState<any>({})
  const [qual, setQual] = useState<any>({})
  const [inv, setInv] = useState<any>({})
  const [daily, setDaily] = useState<any>(null)
  const [top, setTop] = useState<any>(null)

  useEffect(() => {
    getProductionKpi(30).then(d => setProd(d || {})).catch(() => {})
    getQualityKpi(30).then(d => setQual(d || {})).catch(() => {})
    getInventoryKpi().then(d => setInv(d || {})).catch(() => {})
    getDailyProduction(14).then(setDaily).catch(() => {})
    getTopItems(30, 10).then(setTop).catch(() => {})
  }, [])

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-xl font-bold flex items-center gap-2"><BarChart3 className="text-brand" size={20} /> 분석 / KPI</h1>
          <p className="text-sm text-slate-400 mt-0.5">생산 · 품질 · 재고 KPI (BI 피드 연동, 30일)</p>
        </div>
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-6">
        <StatCard label="총 생산량" value={num(prod, 'totalOutput', 'totalQty', 'output')} icon={<Factory size={13} />} color="text-brand" />
        <StatCard label="검사 합격률" value={num(qual, 'passRate', 'rate').toFixed(1)} unit="%" icon={<ScanSearch size={13} />} color="text-accent" />
        <StatCard label="불량률" value={num(qual, 'defectRate').toFixed(2)} unit="%" icon={<TrendingUp size={13} />} color="text-rose-400" />
        <StatCard label="재고 품목수" value={num(inv, 'itemCount', 'totalItems', 'count')} icon={<Boxes size={13} />} color="text-sky-400" />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 mb-4">
        <Card title="일별 생산량 (14일)" icon={<Factory size={15} />}><Chart type="AREA" data={toChart(daily, '생산량')} /></Card>
        <Card title="품목별 생산 TOP (30일)" icon={<TrendingUp size={15} />}><Chart type="BAR" data={toChart(top, '생산량')} /></Card>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        <Card title="생산 KPI" icon={<Factory size={15} />}>
          <KpiList o={prod} />
        </Card>
        <Card title="품질 KPI" icon={<ScanSearch size={15} />}>
          <KpiList o={qual} />
        </Card>
      </div>
    </div>
  )
}

function KpiList({ o }: { o: any }) {
  const entries = Object.entries(o || {}).filter(([, v]) => typeof v === 'number' || typeof v === 'string')
  if (!entries.length) return <p className="text-slate-500 text-sm py-4 text-center">데이터 없음</p>
  return (
    <div className="space-y-1.5">
      {entries.map(([k, v]) => (
        <div key={k} className="flex items-center justify-between text-sm border-b border-edge/40 py-1.5">
          <span className="text-slate-400 text-xs">{k}</span>
          <span className="text-slate-200 font-medium">{typeof v === 'number' ? v.toLocaleString() : String(v)}</span>
        </div>
      ))}
    </div>
  )
}
