import { useEffect, useState } from 'react'
import { Barcode, Plus, AlarmClock } from 'lucide-react'
import StatusBadge from '../components/StatusBadge'
import { PageHeader, Btn, Field, Modal, Empty, Card } from '../components/ui'
import { canWrite } from '../components/rbac'
import {
  getLotSerials, getExpiringLots, createLotSerial, setLotSerialStatus, getItems,
} from '../api/client'

const STATUSES = ['', 'ACTIVE', 'CONSUMED', 'SHIPPED', 'EXPIRED']
const SET_STATES = ['ACTIVE', 'CONSUMED', 'SHIPPED', 'EXPIRED']
const emptyForm = { itemCode: '', lotNo: '', serialNo: '', qty: 0, mfgDate: '', expiryDate: '', status: 'ACTIVE' }

export default function LotSerial() {
  const [list, setList] = useState<any[]>([])
  const [expiring, setExpiring] = useState<any[]>([])
  const [status, setStatus] = useState('')
  const [keyword, setKeyword] = useState('')
  const [editor, setEditor] = useState<any>(null)
  const [items, setItems] = useState<any[]>([])
  const writable = canWrite()

  const load = () => {
    getLotSerials({ status, keyword }).then(d => setList(d || [])).catch(() => setList([]))
    getExpiringLots(30).then(d => setExpiring(Array.isArray(d) ? d : [])).catch(() => setExpiring([]))
  }
  useEffect(() => { load() }, [status])
  useEffect(() => { getItems().then(d => setItems(d || [])).catch(() => {}) }, [])

  const openNew = () => setEditor({ ...emptyForm })
  const save = async () => { await createLotSerial(editor); setEditor(null); load() }
  const changeStatus = async (id: number, s: string) => { await setLotSerialStatus(id, s); load() }

  return (
    <div>
      <PageHeader title="LOT / 시리얼" subtitle="LOT·시리얼 추적 · 유효기간 관리"
        actions={writable && <Btn onClick={openNew}><Plus size={16} /> LOT 등록</Btn>} />

      <Card title="유효기간 임박 (30일)" icon={<AlarmClock size={15} className="text-amber-400" />} className="mb-5">
        <div className="flex flex-wrap gap-2">
          {expiring.map((e: any, i: number) => (
            <div key={i} className="bg-amber-500/5 border border-amber-500/20 rounded-lg px-3 py-2 text-sm">
              <span className="font-mono text-xs text-amber-300">{e.lotNo}</span>
              <span className="text-slate-400 text-xs ml-2">{e.itemName || e.itemCode} · ~{e.expiryDate}</span>
            </div>
          ))}
          {expiring.length === 0 && <p className="text-slate-500 text-sm py-2">임박 LOT 없음</p>}
        </div>
      </Card>

      <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="LOT/품목 검색" 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">LOT</th><th className="text-left">시리얼</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 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"><Barcode size={14} className="text-brand" />{r.lotNo}</td>
                <td className="text-slate-400 font-mono text-xs">{r.serialNo || '-'}</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 text-xs">{r.mfgDate || '-'}</td>
                <td className="text-slate-400 text-xs">{r.expiryDate || '-'}</td>
                <td className="px-4">
                  {writable ? (
                    <select value={r.status} onChange={e => changeStatus(r.id, e.target.value)} className="px-2 py-1 rounded-md bg-ink border border-edge text-xs focus:border-brand outline-none">
                      {SET_STATES.map(s => <option key={s} value={s}>{s}</option>)}
                    </select>
                  ) : <StatusBadge status={r.status} />}
                </td>
              </tr>
            ))}
            {list.length === 0 && <Empty colSpan={7} msg="LOT/시리얼이 없습니다." />}
          </tbody>
        </table>
      </div>

      {editor && (
        <Modal title="LOT / 시리얼 등록" 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="LOT 번호"><input className="inp" value={editor.lotNo} onChange={e => setEditor({ ...editor, lotNo: e.target.value })} /></Field>
              <Field label="시리얼"><input className="inp" value={editor.serialNo} onChange={e => setEditor({ ...editor, serialNo: e.target.value })} /></Field>
            </div>
            <Field label="수량"><input type="number" className="inp" value={editor.qty} onChange={e => setEditor({ ...editor, qty: Number(e.target.value) })} /></Field>
            <div className="grid grid-cols-2 gap-3">
              <Field label="제조일"><input type="date" className="inp" value={editor.mfgDate} onChange={e => setEditor({ ...editor, mfgDate: e.target.value })} /></Field>
              <Field label="유효기간"><input type="date" className="inp" value={editor.expiryDate} onChange={e => setEditor({ ...editor, expiryDate: e.target.value })} /></Field>
            </div>
          </div>
          <div className="flex justify-end gap-2 mt-5">
            <Btn variant="ghost" onClick={() => setEditor(null)}>취소</Btn>
            <Btn onClick={save}>저장</Btn>
          </div>
        </Modal>
      )}
    </div>
  )
}
