import { useEffect, useState } from 'react'
import { Factory, Plus } from 'lucide-react'
import Chart from '../components/Chart'
import { PageHeader, Btn, Field, Modal, Empty, Card } from '../components/ui'
import { canWrite } from '../components/rbac'
import {
  getProductions, reportProduction, getDailyOutput, getDefectPareto,
  getWorkOrders, getItems, getWorkers,
} from '../api/client'

const emptyForm = { woNo: '', itemCode: '', goodQty: 0, defectQty: 0, lotNo: '', workerId: '', remark: '' }

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.defectCode || r.date), series: [{ name, data: raw.map((r: any) => Number(r.value ?? r.count ?? r.qty ?? 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
}

export default function Production() {
  const [list, setList] = useState<any[]>([])
  const [daily, setDaily] = useState<any>(null)
  const [pareto, setPareto] = useState<any>(null)
  const [woNo, setWoNo] = useState('')
  const [editor, setEditor] = useState<any>(null)
  const [workorders, setWorkorders] = useState<any[]>([])
  const [items, setItems] = useState<any[]>([])
  const [workers, setWorkers] = useState<any[]>([])
  const writable = canWrite()

  const load = () => {
    getProductions({ woNo, limit: 100 }).then(d => setList(d || [])).catch(() => setList([]))
    getDailyOutput(14).then(setDaily).catch(() => {})
    getDefectPareto(30).then(setPareto).catch(() => {})
  }
  useEffect(() => { load() }, [])
  useEffect(() => {
    getWorkOrders({ status: 'INPROGRESS' }).then(d => setWorkorders(d || [])).catch(() => {})
    getItems().then(d => setItems(d || [])).catch(() => {})
    getWorkers().then(d => setWorkers(d || [])).catch(() => {})
  }, [])

  const openNew = () => setEditor({ ...emptyForm })
  const save = async () => { await reportProduction(editor); setEditor(null); load() }

  return (
    <div>
      <PageHeader title="생산실적" subtitle="생산실적 보고 · LOT 생성 · 자재 투입 / 산출 입고"
        actions={writable && <Btn onClick={openNew}><Plus size={16} /> 실적 보고</Btn>} />

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 mb-6">
        <Card title="일별 생산량 (14일)" icon={<Factory size={15} />}><Chart type="AREA" data={toChart(daily, '생산량')} /></Card>
        <Card title="불량 파레토 (30일)"><Chart type="BAR" data={toChart(pareto, '불량수')} /></Card>
      </div>

      <div className="flex items-center gap-2 mb-4">
        <input value={woNo} onChange={e => setWoNo(e.target.value)} onKeyDown={e => e.key === 'Enter' && load()} placeholder="작업지시번호" className="inp w-44" />
        <Btn variant="ghost" onClick={load}>검색</Btn>
      </div>

      <div className="bg-card border border-edge rounded-xl overflow-hidden">
        <table className="w-full text-sm">
          <thead className="text-slate-500 text-xs bg-panel">
            <tr><th className="text-left py-3 px-4">작업지시</th><th className="text-left">품목</th><th className="text-left">LOT</th><th className="text-right">양품</th><th className="text-right">불량</th><th className="text-left">작업자</th><th className="text-left">일시</th></tr>
          </thead>
          <tbody>
            {list.map(p => (
              <tr key={p.id} className="border-t border-edge/50">
                <td className="py-3 px-4 font-medium">{p.woNo}</td>
                <td className="text-slate-300 text-xs">{p.itemName || p.itemCode}</td>
                <td className="text-slate-400 font-mono text-xs">{p.lotNo || '-'}</td>
                <td className="text-right text-emerald-400">{Number(p.goodQty || 0).toLocaleString()}</td>
                <td className="text-right text-rose-400">{Number(p.defectQty || 0).toLocaleString()}</td>
                <td className="text-slate-400 text-xs">{p.workerId || '-'}</td>
                <td className="text-slate-500 text-xs">{p.createdAt ? new Date(p.createdAt).toLocaleString('ko-KR') : '-'}</td>
              </tr>
            ))}
            {list.length === 0 && <Empty colSpan={7} msg="생산실적이 없습니다." />}
          </tbody>
        </table>
      </div>

      {editor && (
        <Modal title="생산실적 보고" onClose={() => setEditor(null)}>
          <div className="space-y-3">
            <Field label="작업지시">
              <select className="inp" value={editor.woNo} onChange={e => {
                const wo = workorders.find((w: any) => w.woNo === e.target.value)
                setEditor({ ...editor, woNo: e.target.value, itemCode: wo?.itemCode || editor.itemCode })
              }}>
                <option value="">선택</option>
                {workorders.map((w: any) => <option key={w.id} value={w.woNo}>{w.woNo} · {w.itemName || w.itemCode}</option>)}
              </select>
            </Field>
            <Field label="품목코드">
              <select className="inp" value={editor.itemCode} onChange={e => setEditor({ ...editor, itemCode: e.target.value })}>
                <option value="">선택</option>
                {items.map((it: any) => <option key={it.id} value={it.itemCode}>{it.itemName} ({it.itemCode})</option>)}
              </select>
            </Field>
            <div className="grid grid-cols-2 gap-3">
              <Field label="양품 수량"><input type="number" className="inp" value={editor.goodQty} onChange={e => setEditor({ ...editor, goodQty: Number(e.target.value) })} /></Field>
              <Field label="불량 수량"><input type="number" className="inp" value={editor.defectQty} onChange={e => setEditor({ ...editor, defectQty: Number(e.target.value) })} /></Field>
            </div>
            <div className="grid grid-cols-2 gap-3">
              <Field label="LOT (미입력 시 자동)"><input className="inp" value={editor.lotNo} onChange={e => setEditor({ ...editor, lotNo: e.target.value })} /></Field>
              <Field label="작업자">
                <select className="inp" value={editor.workerId} onChange={e => setEditor({ ...editor, workerId: e.target.value })}>
                  <option value="">선택</option>
                  {workers.map((w: any) => <option key={w.id} value={w.id}>{w.displayName || w.username}</option>)}
                </select>
              </Field>
            </div>
            <Field label="비고"><input className="inp" value={editor.remark} onChange={e => setEditor({ ...editor, remark: e.target.value })} /></Field>
          </div>
          <div className="flex justify-end gap-2 mt-5">
            <Btn variant="ghost" onClick={() => setEditor(null)}>취소</Btn>
            <Btn onClick={save}>보고</Btn>
          </div>
        </Modal>
      )}
    </div>
  )
}
