import { useState } from 'react'
import { Network, Search, ArrowRight, ArrowLeft, History } from 'lucide-react'
import { PageHeader, Btn, Card, Empty } from '../components/ui'
import { getLotHistory, getLotForward, getLotBackward } from '../api/client'

export default function LotTracking() {
  const [lotNo, setLotNo] = useState('')
  const [history, setHistory] = useState<any[]>([])
  const [forward, setForward] = useState<any[]>([])
  const [backward, setBackward] = useState<any[]>([])
  const [loaded, setLoaded] = useState(false)

  const search = async () => {
    if (!lotNo.trim()) return
    setLoaded(true)
    getLotHistory(lotNo).then(d => setHistory(asArr(d))).catch(() => setHistory([]))
    getLotForward(lotNo).then(d => setForward(asArr(d))).catch(() => setForward([]))
    getLotBackward(lotNo).then(d => setBackward(asArr(d))).catch(() => setBackward([]))
  }
  const asArr = (d: any): any[] => Array.isArray(d) ? d : (d?.nodes || d?.items || (d ? [d] : []))

  return (
    <div>
      <PageHeader title="LOT 추적" subtitle="LOT/시리얼 정·역추적 (Genealogy) — 이력 · 정추적(소비처) · 역추적(투입원)" />

      <div className="flex items-center gap-2 mb-6">
        <input value={lotNo} onChange={e => setLotNo(e.target.value)} onKeyDown={e => e.key === 'Enter' && search()} placeholder="LOT 번호 입력 (예: LOT-20260614-001)" className="inp w-80" />
        <Btn onClick={search}><Search size={15} /> 추적</Btn>
      </div>

      {!loaded ? (
        <Empty msg="LOT 번호를 입력하고 추적을 실행하세요." />
      ) : (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
          <Card title="이력 (History)" icon={<History size={15} />}>
            <Timeline rows={history} kind="history" />
          </Card>
          <Card title="정추적 → 소비 작업지시" icon={<ArrowRight size={15} className="text-emerald-400" />}>
            <Timeline rows={forward} kind="forward" />
          </Card>
          <Card title="역추적 ← 투입 LOT" icon={<ArrowLeft size={15} className="text-sky-400" />}>
            <Timeline rows={backward} kind="backward" />
          </Card>
        </div>
      )}
    </div>
  )
}

function Timeline({ rows, kind }: { rows: any[]; kind: string }) {
  if (!rows.length) return <p className="text-slate-500 text-sm py-6 text-center">데이터 없음</p>
  return (
    <div className="space-y-2 max-h-[460px] overflow-auto">
      {rows.map((r: any, i: number) => (
        <div key={i} className="relative pl-4 border-l-2 border-edge">
          <span className="absolute -left-[5px] top-1.5 w-2 h-2 rounded-full bg-brand" />
          <div className="bg-panel border border-edge rounded-lg p-2.5">
            <div className="text-sm font-medium flex items-center gap-1.5">
              <Network size={12} className="text-brand" />
              {r.lotNo || r.woNo || r.itemName || r.itemCode || r.event || `노드 ${i + 1}`}
            </div>
            <div className="text-[11px] text-slate-400 mt-0.5">
              {[r.itemName || r.itemCode, r.woNo, r.eventType || r.txnType || r.refType, r.qty != null ? `${r.qty}` : null]
                .filter(Boolean).join(' · ') || (kind === 'history' ? '이력' : '관계')}
            </div>
            {r.createdAt && <div className="text-[10px] text-slate-500 mt-0.5">{new Date(r.createdAt).toLocaleString('ko-KR')}</div>}
          </div>
        </div>
      ))}
    </div>
  )
}
