import { useEffect, useState } from 'react'
import {
  Truck, Plus, PackageCheck, PackageOpen, ScanSearch, Send, XCircle, FileText,
} from 'lucide-react'
import StatusBadge from '../components/StatusBadge'
import { PageHeader, Btn, Field, Modal, Empty } from '../components/ui'
import { canWrite } from '../components/rbac'
import {
  getShippings, getShippingBoard, getShipping, createShipping, updateShipping,
  pickShipping, packShipping, inspectShipping, shipShipping, cancelShipping,
  getPartners, getItems, getWarehouses,
} from '../api/client'

const STATUSES = ['', 'ORDERED', 'PICKING', 'PACKING', 'INSPECTED', 'SHIPPED', 'CANCELLED']
const emptyForm = {
  partnerCode: '', orderRef: '', itemCode: '', lotNo: '', planQty: 0,
  warehouseCode: '', locationCode: '', inspectionRequired: false, remark: '',
}

export default function Shipping() {
  const [list, setList] = useState<any[]>([])
  const [board, setBoard] = useState<any>(null)
  const [status, setStatus] = useState('')
  const [keyword, setKeyword] = useState('')
  const [editor, setEditor] = useState<any>(null)
  const [detail, setDetail] = useState<any>(null)
  const [partners, setPartners] = useState<any[]>([])
  const [items, setItems] = useState<any[]>([])
  const [warehouses, setWarehouses] = useState<any[]>([])
  const writable = canWrite()

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

  const openNew = () => setEditor({ ...emptyForm, _new: true })
  const openDetail = async (id: number) => { setDetail(await getShipping(id)) }
  const save = async () => {
    const { _new, id, ...payload } = editor
    if (_new) await createShipping(payload); else await updateShipping(id, payload)
    setEditor(null); load()
  }
  const doPick = async (s: any) => {
    const v = window.prompt(`피킹 수량 (계획 ${s.planQty})`, String(s.planQty - (s.pickedQty || 0)))
    if (v == null) return; await pickShipping(s.id, Number(v)); load(); if (detail?.id === s.id) openDetail(s.id)
  }
  const doPack = async (s: any) => {
    const v = window.prompt(`패킹 수량 (피킹 ${s.pickedQty})`, String((s.pickedQty || 0) - (s.packedQty || 0)))
    if (v == null) return; await packShipping(s.id, Number(v)); load(); if (detail?.id === s.id) openDetail(s.id)
  }
  const doInspect = async (s: any, result: 'PASS' | 'FAIL') => { await inspectShipping(s.id, result); load(); if (detail?.id === s.id) openDetail(s.id) }
  const doShip = async (s: any) => {
    if (!window.confirm('출하 확정 시 재고가 차감되고 납품서·거래명세서가 발번됩니다. 진행할까요?')) return
    try { await shipShipping(s.id); load(); setDetail(null) }
    catch (e: any) { window.alert(e?.response?.data?.message === undefined ? '출하 확정 실패' : '출하 확정 실패 — 검사 합격 필요 여부를 확인하세요.') }
  }
  const doCancel = async (s: any) => { if (!window.confirm('취소하시겠습니까?')) return; await cancelShipping(s.id); load(); setDetail(null) }

  const boardCols = [
    { key: 'ORDERED', label: '출하지시' }, { key: 'PICKING', label: '피킹' },
    { key: 'PACKING', label: '패킹' }, { key: 'INSPECTED', label: '검사완료' }, { key: 'SHIPPED', label: '출하완료' },
  ]
  const boardCount = (k: string) => board?.[k] ?? board?.[k.toLowerCase()] ?? 0

  return (
    <div>
      <PageHeader title="출하관리 ★" subtitle="출하지시 · 피킹/패킹 · 출하검사(OQC) · 출하확정(재고감소·납품서·거래명세서)"
        actions={writable && <Btn onClick={openNew}><Plus size={16} /> 출하지시</Btn>} />

      <div className="grid grid-cols-2 lg:grid-cols-5 gap-3 mb-5">
        {boardCols.map(c => (
          <div key={c.key} className="bg-card border border-edge rounded-xl p-4 text-center">
            <div className="text-xs text-slate-400">{c.label}</div>
            <div className="text-2xl font-bold mt-1 text-brand">{boardCount(c.key).toLocaleString()}</div>
          </div>
        ))}
      </div>

      <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="품목/거래처 검색" 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-left">검사</th>
              <th className="text-left">상태</th><th className="text-right px-4">작업</th>
            </tr>
          </thead>
          <tbody>
            {list.map(s => (
              <tr key={s.id} className="border-t border-edge/50 cursor-pointer hover:bg-panel/40" onClick={() => openDetail(s.id)}>
                <td className="py-3 px-4 font-medium flex items-center gap-1.5"><Truck size={14} className="text-brand" />{s.shippingNo}</td>
                <td className="text-slate-400 text-xs">{s.partnerCode}</td>
                <td className="text-slate-300 text-xs">{s.itemName || s.itemCode}</td>
                <td className="text-slate-400 font-mono text-xs">{s.lotNo || '-'}</td>
                <td className="text-right text-slate-300 text-xs">{s.planQty}/{s.pickedQty || 0}/{s.packedQty || 0}</td>
                <td>{s.inspectionRequired ? <StatusBadge status={s.inspectionResult || 'WAIT'} /> : <span className="text-slate-500 text-xs">불필요</span>}</td>
                <td><StatusBadge status={s.status} /></td>
                <td className="px-4" onClick={e => e.stopPropagation()}>
                  <div className="flex items-center justify-end gap-2">
                    {writable && s.status === 'ORDERED' && <button onClick={() => doPick(s)} title="피킹" className="text-sky-400 hover:text-sky-300"><PackageOpen size={15} /></button>}
                    {writable && s.status === 'PICKING' && <button onClick={() => doPack(s)} title="패킹" className="text-violet-400 hover:text-violet-300"><PackageCheck size={15} /></button>}
                    {writable && s.status === 'PACKING' && s.inspectionRequired && <button onClick={() => doInspect(s, 'PASS')} title="출하검사" className="text-cyan-400 hover:text-cyan-300"><ScanSearch size={15} /></button>}
                    {writable && (s.status === 'PACKING' || s.status === 'INSPECTED') && <button onClick={() => doShip(s)} title="출하확정" className="text-emerald-400 hover:text-emerald-300"><Send size={15} /></button>}
                    {writable && s.status !== 'SHIPPED' && s.status !== 'CANCELLED' && <button onClick={() => doCancel(s)} title="취소" className="text-rose-400 hover:text-rose-300"><XCircle size={15} /></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="주문참조"><input className="inp" value={editor.orderRef} onChange={e => setEditor({ ...editor, orderRef: e.target.value })} /></Field>
            </div>
            <div className="grid grid-cols-2 gap-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>
              <Field label="LOT 번호"><input className="inp" value={editor.lotNo} onChange={e => setEditor({ ...editor, lotNo: e.target.value })} /></Field>
            </div>
            <Field label="계획 수량"><input type="number" className="inp" value={editor.planQty} onChange={e => setEditor({ ...editor, planQty: Number(e.target.value) })} /></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>
            <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 })} />
              출하검사(OQC) 필수
            </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>
      )}

      {detail && (
        <Modal title={`출하 상세 — ${detail.shippingNo}`} onClose={() => setDetail(null)} wide>
          <div className="grid grid-cols-2 gap-4 text-sm">
            <Info label="거래처" value={detail.partnerCode} />
            <Info label="상태" value={<StatusBadge status={detail.status} />} />
            <Info label="품목" value={`${detail.itemName || ''} (${detail.itemCode})`} />
            <Info label="LOT" value={detail.lotNo || '-'} />
            <Info label="계획 수량" value={detail.planQty} />
            <Info label="피킹/패킹/출하" value={`${detail.pickedQty || 0} / ${detail.packedQty || 0} / ${detail.shippedQty || 0}`} />
            <Info label="검사 필수" value={detail.inspectionRequired ? `예 (${detail.inspectionResult || '대기'})` : '아니오'} />
            <Info label="창고/로케이션" value={`${detail.warehouseCode || '-'} / ${detail.locationCode || '-'}`} />
            <Info label="납품서" value={detail.deliveryNo || '-'} icon={<FileText size={13} />} />
            <Info label="거래명세서" value={detail.statementNo || '-'} icon={<FileText size={13} />} />
            <Info label="출하일" value={detail.shipDate || '-'} />
            <Info label="비고" value={detail.remark || '-'} />
          </div>
          {writable && detail.status !== 'SHIPPED' && detail.status !== 'CANCELLED' && (
            <div className="flex flex-wrap gap-2 mt-5 justify-end">
              {detail.status === 'ORDERED' && <Btn variant="ghost" onClick={() => doPick(detail)}><PackageOpen size={14} /> 피킹</Btn>}
              {detail.status === 'PICKING' && <Btn variant="ghost" onClick={() => doPack(detail)}><PackageCheck size={14} /> 패킹</Btn>}
              {detail.status === 'PACKING' && detail.inspectionRequired && <>
                <Btn variant="ghost" onClick={() => doInspect(detail, 'PASS')}><ScanSearch size={14} /> 검사 합격</Btn>
                <Btn variant="danger" onClick={() => doInspect(detail, 'FAIL')}><ScanSearch size={14} /> 검사 불합격</Btn>
              </>}
              {(detail.status === 'PACKING' || detail.status === 'INSPECTED') && <Btn onClick={() => doShip(detail)}><Send size={14} /> 출하확정</Btn>}
              <Btn variant="danger" onClick={() => doCancel(detail)}><XCircle size={14} /> 취소</Btn>
            </div>
          )}
        </Modal>
      )}
    </div>
  )
}

function Info({ label, value, icon }: { label: string; value: any; icon?: React.ReactNode }) {
  return (
    <div className="bg-panel border border-edge rounded-lg p-2.5">
      <div className="text-[11px] text-slate-500 mb-0.5 flex items-center gap-1">{icon}{label}</div>
      <div className="text-slate-200">{value}</div>
    </div>
  )
}
