import { useEffect, useState } from 'react'
import { ScanSearch, Plus, Sparkles, CheckCircle2, XCircle } from 'lucide-react'
import StatusBadge from '../components/StatusBadge'
import { PageHeader, Btn, Field, Modal, Empty, Card } from '../components/ui'
import { canWrite } from '../components/rbac'
import {
  getInspections, getInspectionPassRate, createInspection,
  judgeInspection, resultInspection, getItems,
} from '../api/client'

const TYPES = ['', 'IQC', 'IPQC', 'OQC']
const RESULTS = ['', 'PASS', 'FAIL', 'WAIT']
const emptyForm = { inspectionType: 'IQC', itemCode: '', lotNo: '', qty: 0, remark: '' }

export default function Inspection() {
  const [list, setList] = useState<any[]>([])
  const [passRate, setPassRate] = useState<any>(null)
  const [type, setType] = useState('')
  const [result, setResult] = useState('')
  const [editor, setEditor] = useState<any>(null)
  const [judge, setJudge] = useState<any>(null)
  const [items, setItems] = useState<any[]>([])
  const writable = canWrite()

  const load = () => {
    getInspections({ inspectionType: type, result }).then(d => setList(d || [])).catch(() => setList([]))
    getInspectionPassRate(30).then(setPassRate).catch(() => {})
  }
  useEffect(() => { load() }, [type, result])
  useEffect(() => { getItems().then(d => setItems(d || [])).catch(() => {}) }, [])

  const openNew = () => setEditor({ ...emptyForm })
  const save = async () => { await createInspection(editor); setEditor(null); load() }
  const openJudge = (insp: any) => setJudge({ id: insp.id, measured: 0, lsl: '', usl: '', target: '', defectQty: 0, defectCode: '' })
  const doJudge = async () => {
    const { id, ...d } = judge
    await judgeInspection(id, {
      measured: Number(d.measured), lsl: d.lsl === '' ? undefined : Number(d.lsl),
      usl: d.usl === '' ? undefined : Number(d.usl), target: d.target === '' ? undefined : Number(d.target),
      defectQty: Number(d.defectQty), defectCode: d.defectCode || undefined,
    })
    setJudge(null); load()
  }
  const manualResult = async (insp: any, r: 'PASS' | 'FAIL') => {
    let defectQty = 0, defectCode = ''
    if (r === 'FAIL') {
      defectQty = Number(window.prompt('불량 수량', '1') || 0)
      defectCode = window.prompt('불량 코드', '') || ''
    }
    await resultInspection(insp.id, { result: r, defectQty, defectCode }); load()
  }

  const rate = passRate?.passRate ?? passRate?.rate
  return (
    <div>
      <PageHeader title="검사 (IQC / IPQC / OQC)" subtitle="수입·공정·출하 검사 · 합/불 판정 · FAIL 시 NCR 자동생성"
        actions={writable && <Btn onClick={openNew}><Plus size={16} /> 검사 등록</Btn>} />

      {rate != null && (
        <Card title="합격률 (30일)" className="mb-5">
          <div className="flex items-center gap-4">
            <div className="text-4xl font-bold text-accent">{Number(rate).toFixed(1)}%</div>
            <div className="text-sm text-slate-400">합격 {passRate?.passCount ?? 0} / 전체 {passRate?.totalCount ?? passRate?.total ?? 0}</div>
          </div>
        </Card>
      )}

      <div className="flex items-center gap-2 mb-4">
        <select className="inp w-32" value={type} onChange={e => setType(e.target.value)}>{TYPES.map(t => <option key={t} value={t}>{t || '전체 유형'}</option>)}</select>
        <select className="inp w-32" value={result} onChange={e => setResult(e.target.value)}>{RESULTS.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-left">LOT</th><th className="text-right">수량</th><th className="text-left">결과</th><th className="text-right px-4">작업</th></tr>
          </thead>
          <tbody>
            {list.map(insp => (
              <tr key={insp.id} className="border-t border-edge/50">
                <td className="py-3 px-4 font-medium flex items-center gap-1.5"><ScanSearch size={14} className="text-brand" />{insp.inspectionNo || insp.id}</td>
                <td><span className="px-2 py-0.5 rounded bg-brand/15 text-brand text-xs border border-brand/30">{insp.inspectionType}</span></td>
                <td className="text-slate-300 text-xs">{insp.itemName || insp.itemCode}</td>
                <td className="text-slate-400 font-mono text-xs">{insp.lotNo || '-'}</td>
                <td className="text-right text-slate-300">{Number(insp.qty || 0).toLocaleString()}</td>
                <td><StatusBadge status={insp.result || 'WAIT'} /></td>
                <td className="px-4">
                  {writable && (!insp.result || insp.result === 'WAIT') && (
                    <div className="flex items-center justify-end gap-2">
                      <button onClick={() => openJudge(insp)} title="AI 판정 보조" className="text-accent hover:text-accent/80"><Sparkles size={15} /></button>
                      <button onClick={() => manualResult(insp, 'PASS')} title="합격" className="text-emerald-400 hover:text-emerald-300"><CheckCircle2 size={15} /></button>
                      <button onClick={() => manualResult(insp, 'FAIL')} title="불합격" className="text-rose-400 hover:text-rose-300"><XCircle size={15} /></button>
                    </div>
                  )}
                </td>
              </tr>
            ))}
            {list.length === 0 && <Empty colSpan={7} msg="검사 기록이 없습니다." />}
          </tbody>
        </table>
      </div>

      {editor && (
        <Modal title="검사 등록" onClose={() => setEditor(null)}>
          <div className="space-y-3">
            <Field label="검사 유형">
              <select className="inp" value={editor.inspectionType} onChange={e => setEditor({ ...editor, inspectionType: e.target.value })}>
                {['IQC', 'IPQC', 'OQC'].map(t => <option key={t}>{t}</option>)}
              </select>
            </Field>
            <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 type="number" className="inp" value={editor.qty} onChange={e => setEditor({ ...editor, qty: 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>
      )}

      {judge && (
        <Modal title="검사 판정 (AI 보조)" onClose={() => setJudge(null)}>
          <p className="text-xs text-slate-400 mb-3">측정값과 규격(LSL/USL/Target)을 입력하면 PASS/FAIL을 자동 판정합니다. FAIL 시 NCR이 자동 생성됩니다.</p>
          <div className="space-y-3">
            <Field label="측정값"><input type="number" step="any" className="inp" value={judge.measured} onChange={e => setJudge({ ...judge, measured: e.target.value })} /></Field>
            <div className="grid grid-cols-3 gap-3">
              <Field label="LSL"><input type="number" step="any" className="inp" value={judge.lsl} onChange={e => setJudge({ ...judge, lsl: e.target.value })} /></Field>
              <Field label="Target"><input type="number" step="any" className="inp" value={judge.target} onChange={e => setJudge({ ...judge, target: e.target.value })} /></Field>
              <Field label="USL"><input type="number" step="any" className="inp" value={judge.usl} onChange={e => setJudge({ ...judge, usl: e.target.value })} /></Field>
            </div>
            <div className="grid grid-cols-2 gap-3">
              <Field label="불량 수량"><input type="number" className="inp" value={judge.defectQty} onChange={e => setJudge({ ...judge, defectQty: e.target.value })} /></Field>
              <Field label="불량 코드"><input className="inp" value={judge.defectCode} onChange={e => setJudge({ ...judge, defectCode: e.target.value })} /></Field>
            </div>
          </div>
          <div className="flex justify-end gap-2 mt-5">
            <Btn variant="ghost" onClick={() => setJudge(null)}>취소</Btn>
            <Btn onClick={doJudge}><Sparkles size={14} /> 판정</Btn>
          </div>
        </Modal>
      )}
    </div>
  )
}
