import { useEffect, useState } from 'react'
import { Columns3, Search, Play, CheckCircle2, Pause } from 'lucide-react'
import StatusBadge from '../components/StatusBadge'
import { PageHeader, Btn, Empty } from '../components/ui'
import { canWrite } from '../components/rbac'
import { getRunningProcesses, getProcessesByWo, setProcessStatus, getWorkOrders } from '../api/client'

const COLS: { key: string; label: string }[] = [
  { key: 'WAIT', label: '대기' }, { key: 'RUNNING', label: '가동' }, { key: 'DONE', label: '완료' },
]

export default function ProcessBoard() {
  const [procs, setProcs] = useState<any[]>([])
  const [woId, setWoId] = useState('')
  const [workorders, setWorkorders] = useState<any[]>([])
  const writable = canWrite()

  const loadRunning = () => getRunningProcesses().then(d => setProcs(Array.isArray(d) ? d : [])).catch(() => setProcs([]))
  const loadByWo = () => { if (woId) getProcessesByWo(Number(woId)).then(d => setProcs(Array.isArray(d) ? d : [])).catch(() => setProcs([])); else loadRunning() }

  useEffect(() => { loadRunning() }, [])
  useEffect(() => {
    getWorkOrders().then(d => setWorkorders(d || [])).catch(() => {})
    const t = window.setInterval(() => { if (!woId) loadRunning() }, 15000)
    return () => window.clearInterval(t)
  }, [woId])

  const setStatus = async (id: number, status: string) => { await setProcessStatus(id, status); loadByWo() }
  const inCol = (k: string) => procs.filter(p => (p.status || 'WAIT').toUpperCase() === k)

  return (
    <div>
      <PageHeader title="공정진행 칸반" subtitle="공정 실시간 진행 상태 (작업지시 미선택 시 전체 가동 공정 · 15초 갱신)"
        actions={<div className="flex items-center gap-2">
          <select className="inp w-56" value={woId} onChange={e => setWoId(e.target.value)}>
            <option value="">전체 가동 공정</option>
            {workorders.map((w: any) => <option key={w.id} value={w.id}>{w.woNo} · {w.itemName || w.itemCode}</option>)}
          </select>
          <Btn variant="ghost" onClick={loadByWo}><Search size={15} /> 조회</Btn>
        </div>} />

      <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
        {COLS.map(col => (
          <div key={col.key} className="bg-panel border border-edge rounded-xl p-3">
            <div className="flex items-center justify-between mb-2 px-1">
              <StatusBadge status={col.key} /><span className="text-xs text-slate-500">{inCol(col.key).length}</span>
            </div>
            <div className="space-y-2 max-h-[600px] overflow-auto">
              {inCol(col.key).map((p: any) => (
                <div key={p.id} className="bg-card border border-edge rounded-lg p-2.5">
                  <div className="text-sm font-medium flex items-center gap-1.5"><Columns3 size={13} className="text-brand" />{p.processName || p.processCode}</div>
                  <div className="text-[11px] text-slate-400 mt-0.5">{p.woNo || ''} · 순서 {p.opSeq ?? '-'} · {p.equipmentCode || '설비 미지정'}</div>
                  {writable && (
                    <div className="flex gap-1.5 mt-2">
                      {col.key === 'WAIT' && <button onClick={() => setStatus(p.id, 'RUNNING')} className="text-[11px] px-1.5 py-0.5 rounded bg-emerald-500/15 text-emerald-400 border border-emerald-500/30 flex items-center gap-1"><Play size={10} /> 가동</button>}
                      {col.key === 'RUNNING' && <>
                        <button onClick={() => setStatus(p.id, 'WAIT')} className="text-[11px] px-1.5 py-0.5 rounded bg-amber-500/15 text-amber-400 border border-amber-500/30 flex items-center gap-1"><Pause size={10} /> 대기</button>
                        <button onClick={() => setStatus(p.id, 'DONE')} className="text-[11px] px-1.5 py-0.5 rounded bg-brand/15 text-brand border border-brand/30 flex items-center gap-1"><CheckCircle2 size={10} /> 완료</button>
                      </>}
                    </div>
                  )}
                </div>
              ))}
              {inCol(col.key).length === 0 && <p className="text-slate-600 text-xs text-center py-3">-</p>}
            </div>
          </div>
        ))}
      </div>
      {procs.length === 0 && <div className="mt-4"><Empty msg="가동 중 공정이 없습니다. 작업지시를 선택해 공정을 조회하세요." /></div>}
    </div>
  )
}
