import { useEffect, useState } from 'react'
import { PackagePlus, Plus, Check, X } from 'lucide-react'
import StatusBadge from '../components/StatusBadge'
import { PageHeader, Btn, Field, Modal, Empty } from '../components/ui'
import { canWrite } from '../components/rbac'
import {
  getReceivings, createReceiving, acceptReceiving, rejectReceiving,
  getItems, getPartners, getWarehouses,
} from '../api/client'

const STATUSES = ['', 'REQUESTED', 'INSPECTING', 'ACCEPTED', 'REJECTED']
const emptyForm = { partnerCode: '', itemCode: '', qty: 0, lotNo: '', warehouseCode: '', locationCode: '', inspectionRequired: false, remark: '' }

export default function Receiving() {
  const [list, setList] = useState<any[]>([])
  const [status, setStatus] = useState('')
  const [editor, setEditor] = useState<any>(null)
  const [items, setItems] = useState<any[]>([])
  const [partners, setPartners] = useState<any[]>([])
  const [warehouses, setWarehouses] = useState<any[]>([])
  const writable = canWrite()

  const load = () => getReceivings({ status }).then(d => setList(d || [])).catch(() => setList([]))
  useEffect(() => { load() }, [status])
  useEffect(() => {
    getItems().then(d => setItems(d || [])).catch(() => {})
    getPartners({ partnerType: 'SUPPLIER' }).then(d => setPartners(d || [])).catch(() => {})
    getWarehouses().then(d => setWarehouses(d || [])).catch(() => {})
  }, [])

  const openNew = () => setEditor({ ...emptyForm, _new: true })
  const save = async () => { const { _new, ...payload } = editor; await createReceiving(payload); setEditor(null); load() }
  const accept = async (r: any) => { await acceptReceiving(r.id, r.inspectionRequired ? 'PASS' : undefined); load() }
  const reject = async (r: any) => { const reason = window.prompt('반려 사유'); if (reason == null) return; await rejectReceiving(r.id, reason); load() }

  return (
    <div>
      <PageHeader title="입고" subtitle="입고 요청 · 검수 · 입고 LOT · 재고 증가"
        actions={writable && <Btn onClick={openNew}><Plus size={16} /> 입고 요청</Btn>} />

      <div className="flex 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>
      </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-right">수량</th><th className="text-left">LOT</th><th className="text-left">창고</th><th className="text-left">상태</th><th className="text-right px-4">작업</th></tr>
          </thead>
          <tbody>
            {list.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"><PackagePlus size={14} className="text-brand" />{r.receivingNo || r.id}</td>
                <td className="text-slate-400 text-xs">{r.partnerCode}</td>
                <td className="text-slate-300 text-xs">{r.itemName || r.itemCode}</td>
                <td className="text-right text-slate-300">{Number(r.qty || 0).toLocaleString()}</td>
                <td className="text-slate-400 font-mono text-xs">{r.lotNo || '-'}</td>
                <td className="text-slate-400 text-xs">{r.warehouseCode || '-'}</td>
                <td><StatusBadge status={r.status} /></td>
                <td className="px-4">
                  <div className="flex items-center justify-end gap-2">
                    {writable && (r.status === 'REQUESTED' || r.status === 'INSPECTING') && <>
                      <button onClick={() => accept(r)} title="입고 승인" className="text-emerald-400 hover:text-emerald-300"><Check size={16} /></button>
                      <button onClick={() => reject(r)} title="반려" className="text-rose-400 hover:text-rose-300"><X size={16} /></button>
                    </>}
                  </div>
                </td>
              </tr>
            ))}
            {list.length === 0 && <Empty colSpan={8} msg="입고 건이 없습니다." />}
          </tbody>
        </table>
      </div>

      {editor && (
        <Modal title="입고 요청" onClose={() => setEditor(null)}>
          <div className="space-y-3">
            <div className="grid grid-cols-2 gap-3">
              <Field label="공급사">
                <select className="inp" value={editor.partnerCode} onChange={e => setEditor({ ...editor, partnerCode: e.target.value })}>
                  <option value="">선택</option>
                  {partners.map((p: any) => <option key={p.id} value={p.partnerCode}>{p.partnerName || p.partnerCode}</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>
            <div className="grid grid-cols-2 gap-3">
              <Field label="수량"><input type="number" className="inp" value={editor.qty} onChange={e => setEditor({ ...editor, qty: Number(e.target.value) })} /></Field>
              <Field label="LOT (미입력 시 자동)"><input className="inp" value={editor.lotNo} onChange={e => setEditor({ ...editor, lotNo: e.target.value })} /></Field>
            </div>
            <div className="grid grid-cols-2 gap-3">
              <Field label="창고">
                <select className="inp" value={editor.warehouseCode} onChange={e => setEditor({ ...editor, warehouseCode: e.target.value })}>
                  <option value="">선택</option>
                  {warehouses.map((w: any) => <option key={w.id} value={w.warehouseCode}>{w.warehouseName || w.warehouseCode}</option>)}
                </select>
              </Field>
              <Field label="로케이션"><input className="inp" value={editor.locationCode} onChange={e => setEditor({ ...editor, locationCode: e.target.value })} /></Field>
            </div>
            <label className="flex items-center gap-2 text-sm text-slate-300">
              <input type="checkbox" checked={editor.inspectionRequired} onChange={e => setEditor({ ...editor, inspectionRequired: e.target.checked })} /> 수입검사(IQC) 필요
            </label>
            <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>
  )
}
