import { useEffect, useState } from 'react'
import {
  Activity, ClipboardList, AlertTriangle, Gauge, RefreshCw, TrendingUp, Clock,
} from 'lucide-react'
import Chart from '../components/Chart'
import { Card, StatCard, Empty } from '../components/ui'
import StatusBadge from '../components/StatusBadge'
import {
  getProgressSummary, getProgressWorkorders, getProgressLive,
  getPlanVsActual, getProgressDelays,
} from '../api/client'

function pct(v: any) { return Math.max(0, Math.min(100, Number(v) || 0)) }

function ProgressBar({ rate, delayed }: { rate: number; delayed?: boolean }) {
  const c = delayed ? 'bg-rose-500' : rate >= 100 ? 'bg-emerald-500' : 'bg-brand'
  return (
    <div className="w-full bg-ink rounded-full h-2 overflow-hidden">
      <div className={`h-full ${c} transition-all`} style={{ width: `${pct(rate)}%` }} />
    </div>
  )
}

export default function Progress() {
  const [sum, setSum] = useState<any>({})
  const [wos, setWos] = useState<any[]>([])
  const [live, setLive] = useState<any[]>([])
  const [pva, setPva] = useState<any>(null)
  const [delays, setDelays] = useState<any>({ workorders: [], jobs: [] })
  const [filter, setFilter] = useState('')

  const load = () => {
    getProgressSummary().then(d => setSum(d || {})).catch(() => {})
    getProgressWorkorders(filter).then(d => setWos(Array.isArray(d) ? d : [])).catch(() => setWos([]))
    getProgressLive().then(d => setLive(Array.isArray(d) ? d : [])).catch(() => setLive([]))
    getPlanVsActual(30).then(setPva).catch(() => {})
    getProgressDelays().then(d => setDelays(d || { workorders: [], jobs: [] })).catch(() => {})
  }
  useEffect(() => { load() }, [filter])
  useEffect(() => {
    const t = window.setInterval(load, 15000)
    return () => window.clearInterval(t)
  }, [filter])

  const g = (k: string, ...alts: string[]): number => {
    for (const key of [k, ...alts]) if (sum?.[key] != null) return Number(sum[key]) || 0
    return 0
  }

  // plan-vs-actual → 차트
  const pvaChart = (() => {
    if (!pva) return undefined
    if (pva.labels && pva.series) return pva
    if (Array.isArray(pva)) {
      return {
        labels: pva.map((r: any) => r.itemName || r.itemCode),
        series: [
          { name: '계획', data: pva.map((r: any) => Number(r.planQty ?? r.plannedQty ?? 0)) },
          { name: '실적', data: pva.map((r: any) => Number(r.actualQty ?? r.producedQty ?? 0)) },
        ],
      }
    }
    return undefined
  })()

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-xl font-bold flex items-center gap-2"><Activity className="text-brand" size={20} /> 진행관리 ★</h1>
          <p className="text-sm text-slate-400 mt-0.5">진척률 · 계획대비실적 · 실시간 생산현황 · 지연 알림 (15초 자동 갱신)</p>
        </div>
        <button onClick={load} className="flex items-center gap-1.5 text-sm text-slate-400 hover:text-brand"><RefreshCw size={15} /> 새로고침</button>
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-6 gap-3 mb-6">
        <StatCard label="진행 작업지시" value={g('active_workorders', 'activeWorkorders')} icon={<ClipboardList size={13} />} />
        <StatCard label="가공 중" value={g('inprogress_workorders', 'inprogressWorkorders')} icon={<Activity size={13} />} color="text-amber-400" />
        <StatCard label="지연" value={g('delayed_workorders', 'delayedWorkorders')} icon={<AlertTriangle size={13} />} color="text-rose-400" />
        <StatCard label="가동 공정" value={g('running_processes', 'runningProcesses')} icon={<Gauge size={13} />} color="text-emerald-400" />
        <StatCard label="활성 작업" value={g('active_jobs', 'activeJobs')} icon={<TrendingUp size={13} />} color="text-sky-400" />
        <StatCard label="평균 진척률" value={g('avg_progress_rate', 'avgProgressRate').toFixed(1)} unit="%" icon={<Activity size={13} />} color="text-accent" />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4 mb-6">
        {/* 작업지시별 진척률 */}
        <Card title="작업지시별 진척률" icon={<ClipboardList size={15} />} className="lg:col-span-2">
          <div className="flex items-center gap-2 mb-3">
            <select className="inp w-40" value={filter} onChange={e => setFilter(e.target.value)}>
              {['', 'RELEASED', 'INPROGRESS', 'DONE'].map(s => <option key={s} value={s}>{s || '전체 상태'}</option>)}
            </select>
          </div>
          <div className="space-y-2.5 max-h-[360px] overflow-auto">
            {wos.map((w: any, i: number) => {
              const rate = Number(w.progressRate ?? w.progress_rate ?? 0)
              const delayed = !!(w.delayed ?? w.isDelayed)
              return (
                <div key={w.id ?? i} className="bg-panel border border-edge rounded-lg p-3">
                  <div className="flex items-center justify-between mb-1.5">
                    <span className="text-sm font-medium">{w.woNo} <span className="text-slate-400 text-xs ml-1">{w.itemName || w.itemCode}</span></span>
                    <div className="flex items-center gap-2">
                      {delayed && <StatusBadge status="DELAYED" />}
                      <span className={`text-sm font-bold ${delayed ? 'text-rose-400' : rate >= 100 ? 'text-emerald-400' : 'text-brand'}`}>{rate.toFixed(0)}%</span>
                    </div>
                  </div>
                  <ProgressBar rate={rate} delayed={delayed} />
                  <div className="text-[11px] text-slate-500 mt-1">실적 {Number(w.producedQty ?? w.actualQty ?? 0).toLocaleString()} / 계획 {Number(w.planQty ?? w.plannedQty ?? 0).toLocaleString()}</div>
                </div>
              )
            })}
            {wos.length === 0 && <Empty msg="진행 중 작업지시가 없습니다." />}
          </div>
        </Card>

        {/* 실시간 가동 공정 */}
        <Card title="실시간 가동 공정" icon={<Activity size={15} />}>
          <div className="space-y-2 max-h-[400px] overflow-auto">
            {live.map((p: any, i: number) => (
              <div key={p.id ?? i} className="bg-panel border border-edge rounded-lg p-2.5">
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium">{p.processName || p.processCode}</span>
                  <span className="flex items-center gap-1 text-[11px] text-emerald-400"><span className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse" />RUNNING</span>
                </div>
                <div className="text-[11px] text-slate-400 mt-0.5">{p.woNo} · {p.equipmentCode || '설비 미지정'}</div>
              </div>
            ))}
            {live.length === 0 && <p className="text-slate-500 text-xs py-6 text-center">가동 중 공정 없음</p>}
          </div>
        </Card>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        <Card title="품목별 계획 대비 실적 (30일)" icon={<TrendingUp size={15} />}>
          <Chart type="BAR" data={pvaChart} />
        </Card>
        <Card title="지연 알림" icon={<Clock size={15} />}>
          <div className="space-y-1.5 max-h-[280px] overflow-auto">
            {(delays.workorders || []).map((w: any, i: number) => (
              <div key={`wo${i}`} className="flex items-center justify-between bg-rose-500/5 border border-rose-500/20 rounded p-2 text-sm">
                <span><AlertTriangle size={13} className="inline text-rose-400 mr-1.5" />{w.woNo} · {w.itemName || w.itemCode}</span>
                <span className="text-rose-400 text-xs">작업지시 지연</span>
              </div>
            ))}
            {(delays.jobs || []).map((j: any, i: number) => (
              <div key={`job${i}`} className="flex items-center justify-between bg-amber-500/5 border border-amber-500/20 rounded p-2 text-sm">
                <span><Clock size={13} className="inline text-amber-400 mr-1.5" />{j.jobNo} · {j.processName || j.processCode}</span>
                <span className="text-amber-400 text-xs">작업 지연</span>
              </div>
            ))}
            {(delays.workorders || []).length === 0 && (delays.jobs || []).length === 0 &&
              <p className="text-slate-500 text-sm py-6 text-center">지연 항목이 없습니다.</p>}
          </div>
        </Card>
      </div>
    </div>
  )
}
