import { useEffect, useState } from 'react'
import { ListChecks, Plus } from 'lucide-react'
import StatusBadge from '../components/StatusBadge'
import { PageHeader, Btn, Field, Modal, Empty } from '../components/ui'
import { canWrite } from '../components/rbac'
import { getCapas, createCapa, updateCapa, transitionCapa } from '../api/client'

const STATUSES = ['', 'OPEN', 'INPROGRESS', 'VERIFY', 'CLOSED']
const TYPES = ['', 'CORRECTIVE', 'PREVENTIVE']
const FLOW: Record<string, string> = { OPEN: 'INPROGRESS', INPROGRESS: 'VERIFY', VERIFY: 'CLOSED' }
const emptyForm = { ncrNo: '', title: '', capaType: 'CORRECTIVE', rootCause: '', actionPlan: '', owner: '', dueDate: '' }

export default function Capa() {
  const [list, setList] = useState<any[]>([])
  const [status, setStatus] = useState('')
  const [capaType, setCapaType] = useState('')
  const [editor, setEditor] = useState<any>(null)
  const writable = canWrite()

  const load = () => getCapas({ status, capaType }).then(d => setList(d || [])).catch(() => setList([]))
  useEffect(() => { load() }, [status, capaType])

  const openNew = () => setEditor({ ...emptyForm, _new: true })
  const save = async () => {
    const { _new, id, ...payload } = editor
    if (_new) await createCapa(payload); else await updateCapa(id, payload)
    setEditor(null); load()
  }
  const advance = async (c: any) => {
    const next = FLOW[c.status]; if (!next) return
    let effectiveness
    if (next === 'CLOSED') { effectiveness = window.prompt('효과성 평가 (예: EFFECTIVE/INEFFECTIVE)', 'EFFECTIVE') || undefined }
    await transitionCapa(c.id, { status: next, effectiveness }); load()
  }

  return (
    <div>
      <PageHeader title="시정조치 CAPA" subtitle="시정·예방조치(8D) · 근본원인 · 조치계획 · 효과성 검증"
        actions={writable && <Btn onClick={openNew}><Plus size={16} /> CAPA 등록</Btn>} />

      <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-40" value={capaType} onChange={e => setCapaType(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">CAPA</th><th className="text-left">제목</th><th className="text-left">유형</th><th className="text-left">NCR</th><th className="text-left">담당</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">
                <td className="py-3 px-4 font-medium flex items-center gap-1.5"><ListChecks size={14} className="text-brand" />{c.capaNo || c.id}</td>
                <td className="text-slate-300 text-xs max-w-[220px] truncate">{c.title}</td>
                <td><span className="px-2 py-0.5 rounded bg-brand/15 text-brand text-xs border border-brand/30">{c.capaType}</span></td>
                <td className="text-slate-400 text-xs">{c.ncrNo || '-'}</td>
                <td className="text-slate-400 text-xs">{c.owner || '-'}</td>
                <td className="text-slate-400 text-xs">{c.dueDate || '-'}</td>
                <td><StatusBadge status={c.status} /></td>
                <td className="px-4">
                  <div className="flex items-center justify-end gap-2">
                    {writable && <button onClick={() => setEditor({ ...c, _new: false })} className="text-xs text-slate-400 hover:text-brand">편집</button>}
                    {writable && FLOW[c.status] && <button onClick={() => advance(c)} className="text-xs text-brand hover:underline">→ {FLOW[c.status]}</button>}
                  </div>
                </td>
              </tr>
            ))}
            {list.length === 0 && <Empty colSpan={8} msg="CAPA가 없습니다." />}
          </tbody>
        </table>
      </div>

      {editor && (
        <Modal title={editor._new ? 'CAPA 등록' : 'CAPA 편집'} onClose={() => setEditor(null)} wide>
          <div className="space-y-3">
            <div className="grid grid-cols-2 gap-3">
              <Field label="제목"><input className="inp" value={editor.title} onChange={e => setEditor({ ...editor, title: e.target.value })} /></Field>
              <Field label="유형">
                <select className="inp" value={editor.capaType} onChange={e => setEditor({ ...editor, capaType: e.target.value })}>
                  {['CORRECTIVE', 'PREVENTIVE'].map(t => <option key={t}>{t}</option>)}
                </select>
              </Field>
            </div>
            <div className="grid grid-cols-3 gap-3">
              <Field label="연계 NCR"><input className="inp" value={editor.ncrNo} onChange={e => setEditor({ ...editor, ncrNo: e.target.value })} /></Field>
              <Field label="담당자"><input className="inp" value={editor.owner} onChange={e => setEditor({ ...editor, owner: e.target.value })} /></Field>
              <Field label="기한"><input type="date" className="inp" value={editor.dueDate || ''} onChange={e => setEditor({ ...editor, dueDate: e.target.value })} /></Field>
            </div>
            <Field label="근본 원인 (Root Cause)"><textarea className="inp" value={editor.rootCause} onChange={e => setEditor({ ...editor, rootCause: e.target.value })} /></Field>
            <Field label="조치 계획 (Action Plan)"><textarea className="inp" value={editor.actionPlan} onChange={e => setEditor({ ...editor, actionPlan: 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>
  )
}
