import { useEffect, useState } from 'react'
import { Route as RouteIcon, Plus, Trash2, Search } from 'lucide-react'
import { PageHeader, Btn, Field, Modal, Empty } from '../components/ui'
import { canManage } from '../components/rbac'
import { getRoutings, createRouting, updateRouting, deleteRouting, getItems, getEquipment } from '../api/client'

const emptyForm = { itemCode: '', opSeq: 1, processCode: '', processName: '', equipmentCode: '', stdTimeMin: 0 }

export default function Routing() {
  const [list, setList] = useState<any[]>([])
  const [itemCode, setItemCode] = useState('')
  const [editor, setEditor] = useState<any>(null)
  const [items, setItems] = useState<any[]>([])
  const [equipment, setEquipment] = useState<any[]>([])
  const manageable = canManage()

  const load = () => getRoutings(itemCode).then(d => setList(d || [])).catch(() => setList([]))
  useEffect(() => { load() }, [itemCode])
  useEffect(() => {
    getItems({ itemType: 'PRODUCT' }).then(d => setItems(d || [])).catch(() => {})
    getEquipment().then(d => setEquipment(d || [])).catch(() => {})
  }, [])

  const openNew = () => setEditor({ ...emptyForm, itemCode, _new: true })
  const save = async () => {
    const { _new, id, ...payload } = editor
    if (_new) await createRouting(payload); else await updateRouting(id, payload)
    setEditor(null); load()
  }
  const remove = async (id: number) => { if (!window.confirm('삭제하시겠습니까?')) return; await deleteRouting(id); load() }

  const sorted = [...list].sort((a, b) => (a.opSeq || 0) - (b.opSeq || 0))

  return (
    <div>
      <PageHeader title="라우팅" subtitle="공정 순서 · 표준시간 · 설비 매핑"
        actions={manageable && <Btn onClick={openNew}><Plus size={16} /> 공정</Btn>} />

      <div className="flex items-center gap-2 mb-4">
        <select className="inp w-56" value={itemCode} onChange={e => setItemCode(e.target.value)}>
          <option value="">전체 / 품목 선택</option>
          {items.map((it: any) => <option key={it.id} value={it.itemCode}>{it.itemName} ({it.itemCode})</option>)}
        </select>
        <Btn variant="ghost" onClick={load}><Search size={15} /> 조회</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">공정코드</th><th className="text-left">공정명</th><th className="text-left">설비</th><th className="text-right">표준시간(분)</th><th className="text-right px-4">작업</th></tr>
          </thead>
          <tbody>
            {sorted.map(r => (
              <tr key={r.id} className="border-t border-edge/50">
                <td className="py-3 px-4 font-medium flex items-center gap-1.5"><RouteIcon size={14} className="text-brand" />{r.opSeq}</td>
                <td className="text-slate-300 text-xs">{r.itemCode}</td>
                <td className="text-slate-400 text-xs">{r.processCode}</td>
                <td className="text-slate-300 text-xs">{r.processName || '-'}</td>
                <td className="text-slate-400 text-xs">{r.equipmentCode || '-'}</td>
                <td className="text-right text-slate-300">{r.stdTimeMin ?? '-'}</td>
                <td className="px-4">
                  {manageable && <div className="flex items-center justify-end gap-2">
                    <button onClick={() => setEditor({ ...r, _new: false })} className="text-xs text-slate-400 hover:text-brand">편집</button>
                    <button onClick={() => remove(r.id)} className="text-rose-400 hover:text-rose-300"><Trash2 size={14} /></button>
                  </div>}
                </td>
              </tr>
            ))}
            {sorted.length === 0 && <Empty colSpan={7} msg="라우팅이 없습니다." />}
          </tbody>
        </table>
      </div>

      {editor && (
        <Modal title={editor._new ? '공정 추가' : '공정 편집'} onClose={() => setEditor(null)}>
          <div className="space-y-3">
            <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.opSeq} onChange={e => setEditor({ ...editor, opSeq: Number(e.target.value) })} /></Field>
              <Field label="표준시간(분)"><input type="number" step="any" className="inp" value={editor.stdTimeMin} onChange={e => setEditor({ ...editor, stdTimeMin: Number(e.target.value) })} /></Field>
            </div>
            <div className="grid grid-cols-2 gap-3">
              <Field label="공정코드"><input className="inp" value={editor.processCode} onChange={e => setEditor({ ...editor, processCode: e.target.value })} /></Field>
              <Field label="공정명"><input className="inp" value={editor.processName} onChange={e => setEditor({ ...editor, processName: e.target.value })} /></Field>
            </div>
            <Field label="설비">
              <select className="inp" value={editor.equipmentCode} onChange={e => setEditor({ ...editor, equipmentCode: e.target.value })}>
                <option value="">미지정</option>
                {equipment.map((eq: any) => <option key={eq.id} value={eq.equipmentCode}>{eq.equipmentName || eq.equipmentCode}</option>)}
              </select>
            </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>
  )
}
