import { useEffect, useState } from 'react'
import { ClipboardCheck, Plus, Wrench } from 'lucide-react'
import StatusBadge from '../components/StatusBadge'
import { PageHeader, Btn, Field, Modal, Empty } from '../components/ui'
import { canWrite, canManage } from '../components/rbac'
import {
  getStocktakes, countStocktake, adjustStocktake, getItems, getWarehouses,
} from '../api/client'

const STATUSES = ['', 'COUNTED', 'ADJUSTED']
const emptyForm = { itemCode: '', warehouseCode: '', locationCode: '', lotNo: '', countedQty: 0, remark: '' }

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

  const load = () => getStocktakes({ status }).then(d => setList(d || [])).catch(() => setList([]))
  useEffect(() => { load() }, [status])
  useEffect(() => {
    getItems().then(d => setItems(d || [])).catch(() => {})
    getWarehouses().then(d => setWarehouses(d || [])).catch(() => {})
  }, [])

  const openNew = () => setEditor({ ...emptyForm })
  const save = async () => { await countStocktake(editor); setEditor(null); load() }
  const adjust = async (id: number) => { if (!window.confirm('재고를 실사 수량으로 보정하시겠습니까?')) return; await adjustStocktake(id); load() }

  return (
    <div>
      <PageHeader title="재고실사" subtitle="실사 카운트 · 시스템 재고 대비 차이 계산 · 재고 보정(ADJUST)"
        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-right">실사</th><th className="text-right">차이</th><th className="text-left">상태</th><th className="text-right px-4">작업</th></tr>
          </thead>
          <tbody>
            {list.map(s => {
              const diff = Number(s.diffQty ?? ((s.countedQty || 0) - (s.systemQty || 0)))
              return (
                <tr key={s.id} className="border-t border-edge/50">
                  <td className="py-3 px-4 font-medium flex items-center gap-1.5"><ClipboardCheck size={14} className="text-brand" />{s.stocktakeNo || s.id}</td>
                  <td className="text-slate-300 text-xs">{s.itemName || s.itemCode}</td>
                  <td className="text-slate-400 text-xs">{s.warehouseCode || '-'} / {s.locationCode || '-'}</td>
                  <td className="text-right text-slate-300">{Number(s.systemQty || 0).toLocaleString()}</td>
                  <td className="text-right text-slate-300">{Number(s.countedQty || 0).toLocaleString()}</td>
                  <td className={`text-right font-medium ${diff === 0 ? 'text-slate-400' : diff > 0 ? 'text-emerald-400' : 'text-rose-400'}`}>{diff > 0 ? '+' : ''}{diff.toLocaleString()}</td>
                  <td><StatusBadge status={s.status} /></td>
                  <td className="px-4 text-right">
                    {manageable && s.status === 'COUNTED' && <button onClick={() => adjust(s.id)} className="inline-flex items-center gap-1 text-xs text-brand hover:underline"><Wrench size={12} /> 보정</button>}
                  </td>
                </tr>
              )
            })}
            {list.length === 0 && <Empty colSpan={8} msg="실사 기록이 없습니다." />}
          </tbody>
        </table>
      </div>

      {editor && (
        <Modal title="실사 카운트" 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="창고">
                <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>
            <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 type="number" className="inp" value={editor.countedQty} onChange={e => setEditor({ ...editor, countedQty: Number(e.target.value) })} /></Field>
            </div>
            <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>
  )
}
