import { useEffect, useState } from 'react'
import { ClipboardList, Plus, Trash2, ChevronRight, Columns3 } from 'lucide-react'
import StatusBadge from '../components/StatusBadge'
import { PageHeader, Btn, Field, Modal, Empty } from '../components/ui'
import { canWrite, canManage } from '../components/rbac'
import {
  getWorkOrders, getWorkOrderKanban, createWorkOrder, updateWorkOrder,
  transitionWorkOrder, deleteWorkOrder, getItems,
} from '../api/client'

const STATUSES = ['', 'CREATED', 'RELEASED', 'INPROGRESS', 'DONE', 'CLOSED', 'CANCELLED']
const KANBAN_COLS = ['CREATED', 'RELEASED', 'INPROGRESS', 'DONE', 'CLOSED']
const emptyForm = { itemCode: '', planQty: 0, dueDate: '', priority: 'NORMAL', remark: '' }

const ACTIONS: Record<string, { action: string; label: string; manager?: boolean }[]> = {
  CREATED: [{ action: 'RELEASE', label: '확정', manager: true }, { action: 'CANCEL', label: '취소', manager: true }],
  RELEASED: [{ action: 'START', label: '착수' }, { action: 'CANCEL', label: '취소', manager: true }],
  INPROGRESS: [{ action: 'COMPLETE', label: '완료' }],
  DONE: [{ action: 'CLOSE', label: '마감', manager: true }],
}

export default function WorkOrders() {
  const [list, setList] = useState<any[]>([])
  const [kanban, setKanban] = useState<any>(null)
  const [view, setView] = useState<'table' | 'kanban'>('table')
  const [status, setStatus] = useState('')
  const [keyword, setKeyword] = useState('')
  const [editor, setEditor] = useState<any>(null)
  const [items, setItems] = useState<any[]>([])
  const writable = canWrite()
  const manageable = canManage()

  const load = () => {
    getWorkOrders({ status, keyword }).then(d => setList(d || [])).catch(() => setList([]))
    getWorkOrderKanban().then(setKanban).catch(() => {})
  }
  useEffect(() => { load() }, [status])
  useEffect(() => { getItems({ itemType: 'PRODUCT' }).then(d => setItems(d || [])).catch(() => {}) }, [])

  const openNew = () => setEditor({ ...emptyForm, _new: true })
  const save = async () => {
    const { _new, id, ...payload } = editor
    if (_new) await createWorkOrder(payload); else await updateWorkOrder(id, payload)
    setEditor(null); load()
  }
  const remove = async (id: number) => { if (!window.confirm('삭제하시겠습니까?')) return; await deleteWorkOrder(id); load() }
  const act = async (id: number, action: string) => { await transitionWorkOrder(id, action); load() }

  const kanbanData = (col: string): any[] => {
    if (!kanban) return list.filter(w => w.status === col)
    return kanban[col] || kanban[col.toLowerCase()] || []
  }

  return (
    <div>
      <PageHeader title="작업지시" subtitle="생산 작업지시 발행 · 상태 전이 · 칸반"
        actions={<>
          <Btn variant="ghost" onClick={() => setView(view === 'table' ? 'kanban' : 'table')}><Columns3 size={15} /> {view === 'table' ? '칸반' : '테이블'}</Btn>
          {writable && <Btn onClick={openNew}><Plus size={16} /> 작업지시</Btn>}
        </>} />

      {view === 'table' ? (
        <>
          <div className="flex flex-wrap items-center gap-2 mb-4">
            <select className="inp w-36" value={status} onChange={e => setStatus(e.target.value)}>
              {STATUSES.map(t => <option key={t} value={t}>{t || '전체 상태'}</option>)}
            </select>
            <input value={keyword} onChange={e => setKeyword(e.target.value)} onKeyDown={e => e.key === 'Enter' && load()} placeholder="품목 검색" className="inp w-52" />
            <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-right">계획수량</th><th className="text-left">납기</th><th className="text-left">우선순위</th><th className="text-left">상태</th><th className="text-right px-4">작업</th></tr>
              </thead>
              <tbody>
                {list.map(w => (
                  <tr key={w.id} className="border-t border-edge/50">
                    <td className="py-3 px-4 font-medium flex items-center gap-1.5"><ClipboardList size={14} className="text-brand" />{w.woNo}</td>
                    <td className="text-slate-300 text-xs">{w.itemName || w.itemCode}</td>
                    <td className="text-right text-slate-300">{Number(w.planQty || 0).toLocaleString()}</td>
                    <td className="text-slate-400 text-xs">{w.dueDate || '-'}</td>
                    <td className="text-slate-400 text-xs">{w.priority || 'NORMAL'}</td>
                    <td><StatusBadge status={w.status} /></td>
                    <td className="px-4">
                      <div className="flex items-center justify-end gap-2">
                        {writable && (ACTIONS[w.status] || []).filter(a => !a.manager || manageable).map(a => (
                          <button key={a.action} onClick={() => act(w.id, a.action)} className="text-xs text-brand hover:underline">{a.label}</button>
                        ))}
                        {writable && w.status === 'CREATED' && <button onClick={() => setEditor({ ...w, _new: false })} className="text-xs text-slate-400 hover:text-brand">편집</button>}
                        {manageable && <button onClick={() => remove(w.id)} className="text-rose-400 hover:text-rose-300"><Trash2 size={14} /></button>}
                      </div>
                    </td>
                  </tr>
                ))}
                {list.length === 0 && <Empty colSpan={7} msg="작업지시가 없습니다." />}
              </tbody>
            </table>
          </div>
        </>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-3 xl:grid-cols-5 gap-3">
          {KANBAN_COLS.map(col => (
            <div key={col} className="bg-panel border border-edge rounded-xl p-3">
              <div className="flex items-center justify-between mb-2 px-1">
                <StatusBadge status={col} />
                <span className="text-xs text-slate-500">{kanbanData(col).length}</span>
              </div>
              <div className="space-y-2 max-h-[600px] overflow-auto">
                {kanbanData(col).map((w: any) => (
                  <div key={w.id} className="bg-card border border-edge rounded-lg p-2.5">
                    <div className="text-sm font-medium flex items-center gap-1"><ChevronRight size={12} className="text-brand" />{w.woNo}</div>
                    <div className="text-[11px] text-slate-400 mt-0.5">{w.itemName || w.itemCode}</div>
                    <div className="text-[11px] text-slate-500 mt-0.5">계획 {Number(w.planQty || 0).toLocaleString()} · 납기 {w.dueDate || '-'}</div>
                    {writable && (
                      <div className="flex gap-1.5 mt-2">
                        {(ACTIONS[w.status] || []).filter(a => !a.manager || manageable).map(a => (
                          <button key={a.action} onClick={() => act(w.id, a.action)} className="text-[11px] px-1.5 py-0.5 rounded bg-brand/15 text-brand border border-brand/30">{a.label}</button>
                        ))}
                      </div>
                    )}
                  </div>
                ))}
                {kanbanData(col).length === 0 && <p className="text-slate-600 text-xs text-center py-3">-</p>}
              </div>
            </div>
          ))}
        </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.planQty} onChange={e => setEditor({ ...editor, planQty: Number(e.target.value) })} /></Field>
              <Field label="납기"><input type="date" className="inp" value={editor.dueDate || ''} onChange={e => setEditor({ ...editor, dueDate: e.target.value })} /></Field>
            </div>
            <Field label="우선순위">
              <select className="inp" value={editor.priority} onChange={e => setEditor({ ...editor, priority: e.target.value })}>
                {['LOW', 'NORMAL', 'HIGH', 'URGENT'].map(p => <option key={p}>{p}</option>)}
              </select>
            </Field>
            <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>
  )
}
