import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import {
  ClipboardList, Factory, Boxes, Gauge, AlertTriangle, Truck, Activity,
  Sparkles, ArrowRight, CheckCircle2,
} from 'lucide-react'
import Chart from '../components/Chart'
import { Card } from '../components/ui'
import StatusBadge from '../components/StatusBadge'
import {
  getDashboardSummary, getWorkorderStatus, getShippingStatusCard, getEquipmentStatusCard,
  getDailyProduction, getProgressSummary,
} from '../api/client'

const cards = [
  { key: 'activeWorkorders', alt: ['inprogressWorkorders', 'activeWo'], label: '진행 작업지시', icon: ClipboardList, color: 'text-brand' },
  { key: 'todayOutput', alt: ['todayProduction', 'dailyOutput'], label: '금일 생산량', icon: Factory, color: 'text-emerald-400' },
  { key: 'oeePercent', alt: ['oee', 'avgOee'], label: '평균 OEE', icon: Gauge, color: 'text-accent', pct: true },
  { key: 'openNcr', alt: ['ncrOpen', 'defectCount'], label: '미처리 부적합', icon: AlertTriangle, color: 'text-rose-400' },
  { key: 'belowSafety', alt: ['lowStock', 'safetyAlert'], label: '안전재고 미달', icon: Boxes, color: 'text-amber-400' },
  { key: 'pendingShipping', alt: ['openShipping', 'shippingCount'], label: '출하 대기', icon: Truck, color: 'text-sky-400' },
  { key: 'runningProcesses', alt: ['running', 'activeProcesses'], label: '가동 공정', icon: Activity, color: 'text-violet-400' },
  { key: 'equipmentDown', alt: ['downEquipment', 'downCount'], label: '설비 비가동', icon: Gauge, color: 'text-orange-400' },
]

function pick(obj: any, key: string, alts: string[] = []): number {
  if (!obj) return 0
  for (const k of [key, ...alts]) if (obj[k] != null) return Number(obj[k]) || 0
  return 0
}

// {labels,series} 또는 {STATE:n} 형태 모두 차트로
function toChart(raw: any, seriesName: string) {
  if (!raw) return undefined
  if (raw.labels && raw.series) return raw
  const entries = Object.entries(raw).filter(([, v]) => typeof v === 'number')
  if (!entries.length) return undefined
  return { labels: entries.map(e => e[0]), series: [{ name: seriesName, data: entries.map(e => e[1] as number) }] }
}

export default function Dashboard() {
  const [sum, setSum] = useState<any>({})
  const [woStatus, setWoStatus] = useState<any>(null)
  const [shipStatus, setShipStatus] = useState<any>(null)
  const [equipStatus, setEquipStatus] = useState<any>(null)
  const [daily, setDaily] = useState<any>(null)
  const [progress, setProgress] = useState<any>({})

  const load = () => {
    getDashboardSummary().then(d => setSum(d || {})).catch(() => {})
    getProgressSummary().then(d => setProgress(d || {})).catch(() => {})
    getWorkorderStatus().then(setWoStatus).catch(() => {})
    getShippingStatusCard().then(setShipStatus).catch(() => {})
    getEquipmentStatusCard().then(setEquipStatus).catch(() => {})
    getDailyProduction(14).then(setDaily).catch(() => {})
  }
  useEffect(() => {
    load()
    const t = window.setInterval(load, 15000)  // 실시간 폴링
    return () => window.clearInterval(t)
  }, [])

  const merged = { ...progress, ...sum }
  const avgRate = pick(progress, 'avg_progress_rate', ['avgProgressRate', 'avgRate'])

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-xl font-bold">제조 실시간 대시보드</h1>
          <p className="text-sm text-slate-400 mt-0.5">생산 · OEE · 재고 · 품질 통합 모니터링 (15초 자동 갱신)</p>
        </div>
        <Link to="/ai-tools" className="flex items-center gap-1.5 text-sm text-brand hover:underline">
          <Sparkles size={16} /> AI 도구 <ArrowRight size={14} />
        </Link>
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        {cards.map(({ key, alt, label, icon: Icon, color, pct }) => {
          const v = pick(merged, key, alt)
          return (
            <div key={key} className="bg-card border border-edge rounded-xl p-4">
              <div className="flex items-center gap-1.5 text-xs text-slate-400"><Icon size={13} /> {label}</div>
              <div className={`text-2xl font-bold mt-2 ${color}`}>
                {v.toLocaleString()}{pct ? '%' : ''}
              </div>
            </div>
          )
        })}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4 mb-6">
        <Card title="일별 생산량 (14일)" icon={<Factory size={15} />} className="lg:col-span-2">
          <Chart type="AREA" data={toChart(daily, '생산량')} />
        </Card>
        <Card title="평균 진척률" icon={<CheckCircle2 size={15} />}>
          <div className="flex flex-col items-center justify-center h-[240px]">
            <div className="text-5xl font-bold text-accent">{avgRate.toFixed(1)}%</div>
            <div className="text-sm text-slate-400 mt-3">
              진행 {pick(progress, 'inprogress_workorders', ['inprogressWorkorders'])} ·
              지연 <span className="text-rose-400">{pick(progress, 'delayed_workorders', ['delayedWorkorders'])}</span>
            </div>
          </div>
        </Card>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
        <Card title="작업지시 상태" icon={<ClipboardList size={15} />}>
          <Chart type="PIE" data={toChart(woStatus, '작업지시')} height={200} />
        </Card>
        <Card title="출하 상태" icon={<Truck size={15} />}>
          <Chart type="BAR" data={toChart(shipStatus, '출하')} height={200} />
        </Card>
        <Card title="설비 가동 현황" icon={<Gauge size={15} />}>
          {Array.isArray(equipStatus) ? (
            <div className="space-y-1.5 max-h-[200px] overflow-auto">
              {equipStatus.slice(0, 8).map((e: any, i: number) => (
                <div key={i} className="flex items-center justify-between text-sm border-b border-edge/40 pb-1">
                  <span className="text-slate-300">{e.equipmentName || e.equipmentCode || `설비 ${i + 1}`}</span>
                  <StatusBadge status={e.runStatus || e.status} />
                </div>
              ))}
              {equipStatus.length === 0 && <p className="text-slate-500 text-sm py-4 text-center">설비 데이터 없음</p>}
            </div>
          ) : (
            <Chart type="PIE" data={toChart(equipStatus, '설비')} height={200} />
          )}
        </Card>
      </div>
    </div>
  )
}
