import { useEffect, useState } from 'react'
import { AlertTriangle, Plus } from 'lucide-react'
import StatusBadge from '../components/StatusBadge'
import { PageHeader, Btn, Field, Modal, Empty } from '../components/ui'
import { canWrite } from '../components/rbac'
import {
  getNcrs, getNcrBoard, createNcr, dispositionNcr, transitionNcr, getItems,
} from '../api/client'

const STATUSES = ['', 'OPEN', 'REVIEW', 'DISPOSITIONED', 'CLOSED']
const SEVERITIES = ['', 'MINOR', 'MAJOR', 'CRITICAL']
const DISPOSITIONS = ['USE_AS_IS', 'REWORK', 'SCRAP', 'RETURN']
const emptyForm = { itemCode: '', lotNo: '', defectCode: '', severity: 'MINOR', qty: 0, description: '' }

const FLOW: Record<string, string> = { OPEN: 'REVIEW', REVIEW: 'DISPOSITIONED', DISPOSITIONED: 'CLOSED' }

export default function Ncr() {
  const [list, setList] = useState<any[]>([])
  const [board, setBoard] = useState<any>(null)
  const [status, setStatus] = useState('')
  const [severity, setSeverity] = useState('')
  const [editor, setEditor] = useState<any>(null)
  const [items, setItems] = useState<any[]>([])
  const writable = canWrite()

  const load = () => {
    getNcrs({ status, severity }).then(d => setList(d || [])).catch(() => setList([]))
    getNcrBoard().then(setBoard).catch(() => {})
  }
  useEffect(() => { load() }, [status, severity])
  useEffect(() => { getItems().then(d => setItems(d || [])).catch(() => {}) }, [])

  const openNew = () => setEditor({ ...emptyForm })
  const save = async () => { await createNcr(editor); setEditor(null); load() }
  const dispose = async (n: any) => { const d = window.prompt(`처리 방식 (${DISPOSITIONS.join('/')})`, 'REWORK'); if (!d) return; await dispositionNcr(n.id, d); load() }
  const advance = async (n: any) => { const next = FLOW[n.status]; if (!next) return; await transitionNcr(n.id, next); load() }

  const boardCols = ['OPEN', 'REVIEW', 'DISPOSITIONED', 'CLOSED']
  const bc = (k: string) => board?.[k] ?? board?.[k.toLowerCase()] ?? 0

  return (
    <div>
      <PageHeader title="부적합 NCR" subtitle="부적합 보고 · 처리(USE_AS_IS/REWORK/SCRAP/RETURN) · CAPA 연계"
        actions={writable && <Btn onClick={openNew}><Plus size={16} /> NCR 등록</Btn>} />

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

      <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>
        <select className="inp w-32" value={severity} onChange={e => setSeverity(e.target.value)}>{SEVERITIES.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">NCR</th><th className="text-left">품목</th><th className="text-left">불량코드</th><th className="text-left">심각도</th><th className="text-right">수량</th><th className="text-left">상태</th><th className="text-right px-4">작업</th></tr>
          </thead>
          <tbody>
            {list.map(n => (
              <tr key={n.id} className="border-t border-edge/50">
                <td className="py-3 px-4 font-medium flex items-center gap-1.5"><AlertTriangle size={14} className="text-rose-400" />{n.ncrNo || n.id}</td>
                <td className="text-slate-300 text-xs">{n.itemName || n.itemCode}</td>
                <td className="text-slate-400 text-xs">{n.defectCode || '-'}</td>
                <td><StatusBadge status={n.severity} /></td>
                <td className="text-right text-slate-300">{Number(n.qty || 0).toLocaleString()}</td>
                <td><StatusBadge status={n.status} /></td>
                <td className="px-4">
                  <div className="flex items-center justify-end gap-2">
                    {writable && n.status === 'REVIEW' && <button onClick={() => dispose(n)} className="text-xs text-brand hover:underline">처리방식</button>}
                    {writable && FLOW[n.status] && <button onClick={() => advance(n)} className="text-xs text-brand hover:underline">→ {FLOW[n.status]}</button>}
                  </div>
                </td>
              </tr>
            ))}
            {list.length === 0 && <Empty colSpan={7} msg="부적합이 없습니다." />}
          </tbody>
        </table>
      </div>

      {editor && (
        <Modal title="부적합 NCR 등록" 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="LOT"><input className="inp" value={editor.lotNo} onChange={e => setEditor({ ...editor, lotNo: e.target.value })} /></Field>
              <Field label="불량코드"><input className="inp" value={editor.defectCode} onChange={e => setEditor({ ...editor, defectCode: e.target.value })} /></Field>
            </div>
            <div className="grid grid-cols-2 gap-3">
              <Field label="심각도">
                <select className="inp" value={editor.severity} onChange={e => setEditor({ ...editor, severity: e.target.value })}>
                  {['MINOR', 'MAJOR', 'CRITICAL'].map(s => <option key={s}>{s}</option>)}
                </select>
              </Field>
              <Field label="수량"><input type="number" className="inp" value={editor.qty} onChange={e => setEditor({ ...editor, qty: Number(e.target.value) })} /></Field>
            </div>
            <Field label="설명"><textarea className="inp" value={editor.description} onChange={e => setEditor({ ...editor, description: 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>
  )
}
