import { useEffect, useState } from 'react'
import { Package, Plus, Trash2 } from 'lucide-react'
import StatusBadge from '../components/StatusBadge'
import { PageHeader, Btn, Field, Modal, Empty, safeJson, jsonStr } from '../components/ui'
import { canManage } from '../components/rbac'
import { getItems, createItem, updateItem, deleteItem } from '../api/client'

const TYPES = ['', 'RAW', 'SEMI', 'PRODUCT', 'SUBSIDIARY']
const STATUSES = ['', 'ACTIVE', 'INACTIVE']
const emptyForm = { itemCode: '', itemName: '', itemType: 'PRODUCT', unit: 'EA', barcode: '', spec: '', safetyStock: 0, warehouseCode: '', attributes: '', status: 'ACTIVE' }

export default function Items() {
  const [list, setList] = useState<any[]>([])
  const [itemType, setItemType] = useState('')
  const [status, setStatus] = useState('')
  const [keyword, setKeyword] = useState('')
  const [editor, setEditor] = useState<any>(null)
  const manageable = canManage()

  const load = () => getItems({ itemType, status, keyword }).then(d => setList(d || [])).catch(() => setList([]))
  useEffect(() => { load() }, [itemType, status])

  const openNew = () => setEditor({ ...emptyForm, _new: true })
  const openEdit = (it: any) => setEditor({ ...it, attributes: jsonStr(safeJson(it.attributes, {})), _new: false })
  const save = async () => {
    const { _new, id, ...payload } = editor
    if (_new) await createItem(payload); else await updateItem(id, payload)
    setEditor(null); load()
  }
  const remove = async (id: number) => { if (!window.confirm('삭제하시겠습니까?')) return; await deleteItem(id); load() }

  return (
    <div>
      <PageHeader title="품목" subtitle="자재 · 반제품 · 제품 · 부자재 · 바코드 · 안전재고 · 속성(JSON)"
        actions={manageable && <Btn onClick={openNew}><Plus size={16} /> 품목</Btn>} />

      <div className="flex flex-wrap items-center gap-2 mb-4">
        <select className="inp w-36" value={itemType} onChange={e => setItemType(e.target.value)}>{TYPES.map(t => <option key={t} value={t}>{t || '전체 유형'}</option>)}</select>
        <select className="inp w-32" 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-left">유형</th><th className="text-left">단위</th><th className="text-left">바코드</th><th className="text-right">안전재고</th><th className="text-left">상태</th><th className="text-right px-4">작업</th></tr>
          </thead>
          <tbody>
            {list.map(it => (
              <tr key={it.id} className="border-t border-edge/50">
                <td className="py-3 px-4 font-medium flex items-center gap-1.5"><Package size={14} className="text-brand" />{it.itemCode}</td>
                <td className="text-slate-300">{it.itemName}</td>
                <td><span className="px-2 py-0.5 rounded bg-brand/15 text-brand text-xs border border-brand/30">{it.itemType}</span></td>
                <td className="text-slate-400 text-xs">{it.unit}</td>
                <td className="text-slate-400 font-mono text-xs">{it.barcode || '-'}</td>
                <td className="text-right text-slate-300">{Number(it.safetyStock || 0).toLocaleString()}</td>
                <td><StatusBadge status={it.status} /></td>
                <td className="px-4">
                  {manageable && <div className="flex items-center justify-end gap-2">
                    <button onClick={() => openEdit(it)} className="text-xs text-slate-400 hover:text-brand">편집</button>
                    <button onClick={() => remove(it.id)} className="text-rose-400 hover:text-rose-300"><Trash2 size={14} /></button>
                  </div>}
                </td>
              </tr>
            ))}
            {list.length === 0 && <Empty colSpan={8} msg="품목이 없습니다." />}
          </tbody>
        </table>
      </div>

      {editor && (
        <Modal title={editor._new ? '품목 등록' : '품목 편집'} onClose={() => setEditor(null)}>
          <div className="space-y-3">
            <div className="grid grid-cols-2 gap-3">
              <Field label="품목코드"><input className="inp" value={editor.itemCode} onChange={e => setEditor({ ...editor, itemCode: e.target.value })} disabled={!editor._new} /></Field>
              <Field label="품목명"><input className="inp" value={editor.itemName} onChange={e => setEditor({ ...editor, itemName: e.target.value })} /></Field>
            </div>
            <div className="grid grid-cols-3 gap-3">
              <Field label="유형">
                <select className="inp" value={editor.itemType} onChange={e => setEditor({ ...editor, itemType: e.target.value })}>
                  {['RAW', 'SEMI', 'PRODUCT', 'SUBSIDIARY'].map(t => <option key={t}>{t}</option>)}
                </select>
              </Field>
              <Field label="단위"><input className="inp" value={editor.unit} onChange={e => setEditor({ ...editor, unit: e.target.value })} /></Field>
              <Field label="안전재고"><input type="number" className="inp" value={editor.safetyStock} onChange={e => setEditor({ ...editor, safetyStock: Number(e.target.value) })} /></Field>
            </div>
            <div className="grid grid-cols-2 gap-3">
              <Field label="바코드"><input className="inp" value={editor.barcode} onChange={e => setEditor({ ...editor, barcode: e.target.value })} /></Field>
              <Field label="기본 창고"><input className="inp" value={editor.warehouseCode} onChange={e => setEditor({ ...editor, warehouseCode: e.target.value })} /></Field>
            </div>
            <Field label="규격(spec)"><input className="inp" value={editor.spec} onChange={e => setEditor({ ...editor, spec: e.target.value })} /></Field>
            <Field label="속성 (JSON)" hint='예: {"color":"red","grade":"A"}'>
              <textarea className="inp font-mono text-xs" rows={3} value={editor.attributes} onChange={e => setEditor({ ...editor, attributes: e.target.value })} />
            </Field>
            {!editor._new && <Field label="상태">
              <select className="inp" value={editor.status} onChange={e => setEditor({ ...editor, status: e.target.value })}>
                {['ACTIVE', 'INACTIVE'].map(s => <option key={s}>{s}</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>
  )
}
