import { useEffect, useState } from 'react'
import { FileBadge, Plus, Eye } from 'lucide-react'
import { PageHeader, Btn, Field, Modal, Empty, jsonStr, safeJson } from '../components/ui'
import { canWrite } from '../components/rbac'
import { getCertificates, getCertificate, createCertificate, getItems } from '../api/client'

const TYPES = ['', 'COA', 'MSDS', 'TEST_REPORT']
const emptyForm = { certType: 'COA', itemCode: '', lotNo: '', partnerCode: '', content: '' }

export default function Certificate() {
  const [list, setList] = useState<any[]>([])
  const [certType, setCertType] = useState('')
  const [editor, setEditor] = useState<any>(null)
  const [detail, setDetail] = useState<any>(null)
  const [items, setItems] = useState<any[]>([])
  const writable = canWrite()

  const load = () => getCertificates({ certType }).then(d => setList(d || [])).catch(() => setList([]))
  useEffect(() => { load() }, [certType])
  useEffect(() => { getItems().then(d => setItems(d || [])).catch(() => {}) }, [])

  const openNew = () => setEditor({ ...emptyForm })
  const save = async () => { await createCertificate(editor); setEditor(null); load() }
  const openDetail = async (id: number) => setDetail(await getCertificate(id))

  return (
    <div>
      <PageHeader title="성적서 (Certificate)" subtitle="COA · MSDS · 시험성적서 (content JSON)"
        actions={writable && <Btn onClick={openNew}><Plus size={16} /> 성적서 발행</Btn>} />

      <div className="flex items-center gap-2 mb-4">
        <select className="inp w-40" value={certType} onChange={e => setCertType(e.target.value)}>{TYPES.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-left">거래처</th><th className="text-left">발행일</th><th className="text-right px-4">작업</th></tr>
          </thead>
          <tbody>
            {list.map(c => (
              <tr key={c.id} className="border-t border-edge/50 cursor-pointer hover:bg-panel/40" onClick={() => openDetail(c.id)}>
                <td className="py-3 px-4 font-medium flex items-center gap-1.5"><FileBadge size={14} className="text-brand" />{c.certNo || c.id}</td>
                <td><span className="px-2 py-0.5 rounded bg-brand/15 text-brand text-xs border border-brand/30">{c.certType}</span></td>
                <td className="text-slate-300 text-xs">{c.itemName || c.itemCode}</td>
                <td className="text-slate-400 font-mono text-xs">{c.lotNo || '-'}</td>
                <td className="text-slate-400 text-xs">{c.partnerCode || '-'}</td>
                <td className="text-slate-500 text-xs">{c.createdAt ? new Date(c.createdAt).toLocaleDateString('ko-KR') : '-'}</td>
                <td className="px-4 text-right" onClick={e => e.stopPropagation()}>
                  <button onClick={() => openDetail(c.id)} className="text-slate-400 hover:text-brand"><Eye size={15} /></button>
                </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.certType} onChange={e => setEditor({ ...editor, certType: e.target.value })}>
                {['COA', 'MSDS', 'TEST_REPORT'].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 className="inp" value={editor.partnerCode} onChange={e => setEditor({ ...editor, partnerCode: e.target.value })} /></Field>
            </div>
            <Field label="내용 (JSON)" hint='예: {"검사항목":"인장강도","결과":"450MPa","판정":"합격"}'>
              <textarea className="inp font-mono text-xs" rows={5} value={editor.content} onChange={e => setEditor({ ...editor, content: 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.certNo || detail.id}`} onClose={() => setDetail(null)} wide>
          <div className="grid grid-cols-2 gap-3 text-sm mb-4">
            <Info label="유형" value={detail.certType} /><Info label="품목" value={`${detail.itemName || ''} (${detail.itemCode})`} />
            <Info label="LOT" value={detail.lotNo || '-'} /><Info label="거래처" value={detail.partnerCode || '-'} />
          </div>
          <div className="bg-ink border border-edge rounded p-3">
            <div className="text-[11px] text-slate-500 mb-1">내용</div>
            <pre className="text-xs text-slate-300 whitespace-pre-wrap">{jsonStr(safeJson(detail.content, detail.content)) || '-'}</pre>
          </div>
        </Modal>
      )}
    </div>
  )
}

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