import { useEffect, useState } from 'react'
import { Boxes, ArrowLeftRight, AlertTriangle, History } from 'lucide-react'
import { PageHeader, Btn, Field, Modal, Empty, Card } from '../components/ui'
import StatusBadge from '../components/StatusBadge'
import { canWrite } from '../components/rbac'
import {
  getInventory, getBelowSafety, getInventoryTxns, transferInventory,
  getItems, getWarehouses,
} from '../api/client'

export default function Inventory() {
  const [list, setList] = useState<any[]>([])
  const [below, setBelow] = useState<any[]>([])
  const [txns, setTxns] = useState<any[]>([])
  const [keyword, setKeyword] = useState('')
  const [warehouseCode, setWarehouseCode] = useState('')
  const [transfer, setTransfer] = useState<any>(null)
  const [items, setItems] = useState<any[]>([])
  const [warehouses, setWarehouses] = useState<any[]>([])
  const writable = canWrite()

  const load = () => {
    getInventory({ keyword, warehouseCode }).then(d => setList(d || [])).catch(() => setList([]))
    getBelowSafety().then(d => setBelow(Array.isArray(d) ? d : [])).catch(() => setBelow([]))
    getInventoryTxns({ limit: 30 }).then(d => setTxns(Array.isArray(d) ? d : [])).catch(() => setTxns([]))
  }
  useEffect(() => { load() }, [warehouseCode])
  useEffect(() => {
    getItems().then(d => setItems(d || [])).catch(() => {})
    getWarehouses().then(d => setWarehouses(d || [])).catch(() => {})
  }, [])

  const openTransfer = () => setTransfer({ itemCode: '', fromWarehouse: '', toWarehouse: '', fromLocation: '', toLocation: '', qty: 0 })
  const doTransfer = async () => { await transferInventory(transfer); setTransfer(null); load() }

  return (
    <div>
      <PageHeader title="재고" subtitle="로케이션별 재고 · 안전재고 · 재고 이동(transfer) · 수불 원장"
        actions={writable && <Btn onClick={openTransfer}><ArrowLeftRight size={15} /> 재고 이동</Btn>} />

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4 mb-5">
        <Card title="안전재고 미달" icon={<AlertTriangle size={15} className="text-amber-400" />}>
          <div className="space-y-1.5 max-h-44 overflow-auto">
            {below.map((b: any, i: number) => (
              <div key={i} className="flex items-center justify-between bg-amber-500/5 border border-amber-500/20 rounded p-2 text-sm">
                <span>{b.itemName || b.itemCode}</span>
                <span className="text-amber-400 text-xs">{Number(b.qty ?? b.availableQty ?? 0)} / 안전 {Number(b.safetyStock ?? 0)}</span>
              </div>
            ))}
            {below.length === 0 && <p className="text-slate-500 text-xs py-4 text-center">미달 항목 없음</p>}
          </div>
        </Card>
        <Card title="최근 수불 이력" icon={<History size={15} />} className="lg:col-span-2">
          <div className="space-y-1 max-h-44 overflow-auto">
            {txns.map((t: any, i: number) => (
              <div key={i} className="flex items-center justify-between text-xs border-b border-edge/40 py-1">
                <span className="text-slate-300">{t.itemName || t.itemCode}</span>
                <span className="flex items-center gap-2">
                  <StatusBadge status={t.txnType || t.refType} />
                  <span className={Number(t.qty) < 0 ? 'text-rose-400' : 'text-emerald-400'}>{Number(t.qty || 0) > 0 ? '+' : ''}{Number(t.qty || 0).toLocaleString()}</span>
                  <span className="text-slate-500">{t.createdAt ? new Date(t.createdAt).toLocaleDateString('ko-KR') : ''}</span>
                </span>
              </div>
            ))}
            {txns.length === 0 && <p className="text-slate-500 text-xs py-4 text-center">수불 이력 없음</p>}
          </div>
        </Card>
      </div>

      <div className="flex flex-wrap items-center gap-2 mb-4">
        <select className="inp w-44" value={warehouseCode} onChange={e => setWarehouseCode(e.target.value)}>
          <option value="">전체 창고</option>
          {warehouses.map((w: any) => <option key={w.id} value={w.warehouseCode}>{w.warehouseName || w.warehouseCode}</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">LOT</th><th className="text-right">재고수량</th><th className="text-right px-4">안전재고</th></tr>
          </thead>
          <tbody>
            {list.map((r, i) => {
              const qty = Number(r.qty ?? r.availableQty ?? 0)
              const safety = Number(r.safetyStock ?? 0)
              return (
                <tr key={r.id ?? i} className="border-t border-edge/50">
                  <td className="py-3 px-4 font-medium flex items-center gap-1.5"><Boxes size={14} className="text-brand" />{r.itemName || r.itemCode}</td>
                  <td className="text-slate-400 text-xs">{r.warehouseCode || '-'}</td>
                  <td className="text-slate-400 text-xs">{r.locationCode || '-'}</td>
                  <td className="text-slate-400 font-mono text-xs">{r.lotNo || '-'}</td>
                  <td className={`text-right font-medium ${safety > 0 && qty < safety ? 'text-amber-400' : 'text-slate-200'}`}>{qty.toLocaleString()}</td>
                  <td className="text-right px-4 text-slate-500">{safety.toLocaleString()}</td>
                </tr>
              )
            })}
            {list.length === 0 && <Empty colSpan={6} msg="재고가 없습니다." />}
          </tbody>
        </table>
      </div>

      {transfer && (
        <Modal title="재고 이동" onClose={() => setTransfer(null)}>
          <div className="space-y-3">
            <Field label="품목">
              <select className="inp" value={transfer.itemCode} onChange={e => setTransfer({ ...transfer, 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="출발 창고">
                <select className="inp" value={transfer.fromWarehouse} onChange={e => setTransfer({ ...transfer, fromWarehouse: 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="도착 창고">
                <select className="inp" value={transfer.toWarehouse} onChange={e => setTransfer({ ...transfer, toWarehouse: e.target.value })}>
                  <option value="">선택</option>
                  {warehouses.map((w: any) => <option key={w.id} value={w.warehouseCode}>{w.warehouseName || w.warehouseCode}</option>)}
                </select>
              </Field>
            </div>
            <div className="grid grid-cols-2 gap-3">
              <Field label="출발 로케이션"><input className="inp" value={transfer.fromLocation} onChange={e => setTransfer({ ...transfer, fromLocation: e.target.value })} /></Field>
              <Field label="도착 로케이션"><input className="inp" value={transfer.toLocation} onChange={e => setTransfer({ ...transfer, toLocation: e.target.value })} /></Field>
            </div>
            <Field label="이동 수량"><input type="number" className="inp" value={transfer.qty} onChange={e => setTransfer({ ...transfer, qty: Number(e.target.value) })} /></Field>
          </div>
          <div className="flex justify-end gap-2 mt-5">
            <Btn variant="ghost" onClick={() => setTransfer(null)}>취소</Btn>
            <Btn onClick={doTransfer}>이동</Btn>
          </div>
        </Modal>
      )}
    </div>
  )
}
