import { useEffect, useState } from 'react'
import { Ruler, Plus, Trash2, Plus as PlusIcon } from 'lucide-react'
import { PageHeader, Btn, Field, Modal, Empty, safeJson, jsonStr } from '../components/ui'
import { canManage } from '../components/rbac'
import { getSpecs, createSpec, updateSpec, deleteSpec, getItems } from '../api/client'

const TYPES = ['', 'IQC', 'IPQC', 'OQC']
const emptyForm = {
  specCode: '', itemCode: '', inspectionType: 'IQC', characteristic: '',
  lsl: '', usl: '', target: '', unit: '', aql: '', items: [] as any[],
}

export default function Spec() {
  const [list, setList] = useState<any[]>([])
  const [type, setType] = useState('')
  const [editor, setEditor] = useState<any>(null)
  const [items, setItems] = useState<any[]>([])
  const manageable = canManage()

  const load = () => getSpecs({ inspectionType: type }).then(d => setList(d || [])).catch(() => setList([]))
  useEffect(() => { load() }, [type])
  useEffect(() => { getItems().then(d => setItems(d || [])).catch(() => {}) }, [])

  const openNew = () => setEditor({ ...emptyForm, _new: true })
  const openEdit = (s: any) => setEditor({ ...s, items: safeJson(s.items, []), _new: false })
  const save = async () => {
    const { _new, id, items: dyn, ...rest } = editor
    const payload = { ...rest, items: jsonStr(dyn) }
    if (_new) await createSpec(payload); else await updateSpec(id, payload)
    setEditor(null); load()
  }
  const remove = async (id: number) => { if (!window.confirm('삭제하시겠습니까?')) return; await deleteSpec(id); load() }

  // 동적 검사항목
  const addItem = () => setEditor((e: any) => ({ ...e, items: [...e.items, { name: '', lsl: '', usl: '', unit: '' }] }))
  const setItem = (i: number, k: string, v: string) => setEditor((e: any) => { const a = [...e.items]; a[i] = { ...a[i], [k]: v }; return { ...e, items: a } })
  const delItem = (i: number) => setEditor((e: any) => ({ ...e, items: e.items.filter((_: any, j: number) => j !== i) }))

  return (
    <div>
      <PageHeader title="검사기준 (Spec)" subtitle="규격 · LSL/USL/Target · AQL · 동적 검사항목(JSON)"
        actions={manageable && <Btn onClick={openNew}><Plus size={16} /> 검사기준</Btn>} />

      <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>
      </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">특성</th><th className="text-right">LSL</th><th className="text-right">Target</th><th className="text-right">USL</th><th className="text-left">AQL</th><th className="text-right px-4">작업</th></tr>
          </thead>
          <tbody>
            {list.map(s => (
              <tr key={s.id} className="border-t border-edge/50">
                <td className="py-3 px-4 font-medium flex items-center gap-1.5"><Ruler size={14} className="text-brand" />{s.specCode}</td>
                <td className="text-slate-300 text-xs">{s.itemCode}</td>
                <td><span className="px-2 py-0.5 rounded bg-brand/15 text-brand text-xs border border-brand/30">{s.inspectionType}</span></td>
                <td className="text-slate-400 text-xs">{s.characteristic || '-'}</td>
                <td className="text-right text-slate-300">{s.lsl ?? '-'}</td>
                <td className="text-right text-slate-300">{s.target ?? '-'}</td>
                <td className="text-right text-slate-300">{s.usl ?? '-'}</td>
                <td className="text-slate-400 text-xs">{s.aql ?? '-'}</td>
                <td className="px-4">
                  {manageable && <div className="flex items-center justify-end gap-2">
                    <button onClick={() => openEdit(s)} className="text-xs text-slate-400 hover:text-brand">편집</button>
                    <button onClick={() => remove(s.id)} className="text-rose-400 hover:text-rose-300"><Trash2 size={14} /></button>
                  </div>}
                </td>
              </tr>
            ))}
            {list.length === 0 && <Empty colSpan={9} msg="검사기준이 없습니다." />}
          </tbody>
        </table>
      </div>

      {editor && (
        <Modal title={editor._new ? '검사기준 등록' : '검사기준 편집'} onClose={() => setEditor(null)} wide>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-3">
              <div className="grid grid-cols-2 gap-3">
                <Field label="기준코드"><input className="inp" value={editor.specCode} onChange={e => setEditor({ ...editor, specCode: e.target.value })} /></Field>
                <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>
              </div>
              <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="특성"><input className="inp" value={editor.characteristic} onChange={e => setEditor({ ...editor, characteristic: e.target.value })} /></Field>
              <div className="grid grid-cols-3 gap-3">
                <Field label="LSL"><input type="number" step="any" className="inp" value={editor.lsl} onChange={e => setEditor({ ...editor, lsl: e.target.value })} /></Field>
                <Field label="Target"><input type="number" step="any" className="inp" value={editor.target} onChange={e => setEditor({ ...editor, target: e.target.value })} /></Field>
                <Field label="USL"><input type="number" step="any" className="inp" value={editor.usl} onChange={e => setEditor({ ...editor, usl: e.target.value })} /></Field>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <Field label="단위"><input className="inp" value={editor.unit} onChange={e => setEditor({ ...editor, unit: e.target.value })} /></Field>
                <Field label="AQL"><input className="inp" value={editor.aql} onChange={e => setEditor({ ...editor, aql: e.target.value })} /></Field>
              </div>
            </div>

            <div className="bg-card border border-edge rounded-xl p-4">
              <div className="flex items-center justify-between mb-3">
                <h3 className="text-sm font-semibold">동적 검사항목</h3>
                <Btn size="sm" variant="ghost" onClick={addItem}><PlusIcon size={13} /> 항목</Btn>
              </div>
              {editor.items.length === 0 && <p className="text-center text-slate-500 text-xs py-6 border border-dashed border-edge rounded">검사항목을 추가하세요.</p>}
              <div className="space-y-2 max-h-72 overflow-auto">
                {editor.items.map((it: any, i: number) => (
                  <div key={i} className="bg-panel border border-edge rounded p-2">
                    <div className="flex items-center justify-between mb-1.5">
                      <span className="text-[11px] text-brand">항목 #{i + 1}</span>
                      <button onClick={() => delItem(i)} className="text-rose-400 hover:text-rose-300"><Trash2 size={12} /></button>
                    </div>
                    <input placeholder="항목명" className="inp text-xs mb-1.5" value={it.name || ''} onChange={e => setItem(i, 'name', e.target.value)} />
                    <div className="grid grid-cols-3 gap-1.5">
                      <input placeholder="LSL" className="inp text-xs" value={it.lsl || ''} onChange={e => setItem(i, 'lsl', e.target.value)} />
                      <input placeholder="USL" className="inp text-xs" value={it.usl || ''} onChange={e => setItem(i, 'usl', e.target.value)} />
                      <input placeholder="단위" className="inp text-xs" value={it.unit || ''} onChange={e => setItem(i, 'unit', e.target.value)} />
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
          <div className="flex justify-end gap-2 mt-5">
            <Btn variant="ghost" onClick={() => setEditor(null)}>취소</Btn>
            <Btn onClick={save}>저장</Btn>
          </div>
        </Modal>
      )}
    </div>
  )
}
