import { useEffect, useState } from 'react'
import { FileInput, Plus, Trash2, Inbox, ListChecks } from 'lucide-react'
import { PageHeader, Btn, Field, Modal, Empty } from '../components/ui'
import { canWrite } from '../components/rbac'
import { getForms, createForm, updateForm, deleteForm, getFormSubmissions } from '../api/client'

const FIELD_TYPES = ['text', 'email', 'tel', 'textarea', 'select', 'checkbox', 'number']
const emptyForm = { name: '', slug: '', fields: [] as any[], active: true }

export default function Forms() {
  const [list, setList] = useState<any[]>([])
  const [builder, setBuilder] = useState<any>(null)
  const [subFor, setSubFor] = useState<any>(null)
  const [subs, setSubs] = useState<any[]>([])
  const [includeSpam, setIncludeSpam] = useState(false)
  const writable = canWrite()

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

  const openNew = () => setBuilder({ ...emptyForm })
  const openEdit = (f: any) => setBuilder({ ...f, fields: Array.isArray(f.fields) ? f.fields : safeFields(f.fields) })
  const save = async () => {
    if (builder.id) await updateForm(builder.id, builder); else await createForm(builder)
    setBuilder(null); load()
  }
  const remove = async (id: number) => { if (!window.confirm('삭제하시겠습니까?')) return; await deleteForm(id); load() }

  const addField = () => setBuilder((b: any) => ({ ...b, fields: [...b.fields, { name: '', label: '', type: 'text', required: false }] }))
  const setField = (i: number, patch: object) => setBuilder((b: any) => { const f = [...b.fields]; f[i] = { ...f[i], ...patch }; return { ...b, fields: f } })
  const delField = (i: number) => setBuilder((b: any) => ({ ...b, fields: b.fields.filter((_: any, j: number) => j !== i) }))

  const openSubs = async (f: any, spam = false) => {
    setSubFor(f); setIncludeSpam(spam)
    const d = await getFormSubmissions(f.id, spam); setSubs(d || [])
  }

  return (
    <div>
      <PageHeader title="폼빌더" subtitle="필드 정의 · 제출 수집 · AI 스팸 필터"
        actions={writable && <Btn onClick={openNew}><Plus size={16} /> 폼 생성</Btn>} />

      <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 px-4">작업</th></tr>
          </thead>
          <tbody>
            {list.map(f => (
              <tr key={f.id} className="border-t border-edge/50">
                <td className="py-3 px-4 font-medium flex items-center gap-2"><FileInput size={15} className="text-brand" />{f.name}</td>
                <td className="text-slate-400 font-mono text-xs">{f.slug}</td>
                <td className="text-slate-400">{(Array.isArray(f.fields) ? f.fields : safeFields(f.fields)).length}</td>
                <td>{f.active ? '활성' : '비활성'}</td>
                <td className="px-4"><div className="flex items-center justify-end gap-3">
                  <button onClick={() => openSubs(f)} title="제출 내역" className="text-slate-400 hover:text-brand"><Inbox size={15} /></button>
                  {writable && <button onClick={() => openEdit(f)} className="text-slate-400 hover:text-brand text-xs">편집</button>}
                  {writable && <button onClick={() => remove(f.id)} className="text-rose-400 hover:text-rose-300"><Trash2 size={15} /></button>}
                </div></td>
              </tr>
            ))}
            {list.length === 0 && <Empty colSpan={5} msg="폼이 없습니다." />}
          </tbody>
        </table>
      </div>

      {builder && (
        <Modal title={builder.id ? '폼 편집' : '폼 생성'} onClose={() => setBuilder(null)} wide>
          <div className="grid grid-cols-2 gap-3 mb-4">
            <Field label="이름"><input className="inp" value={builder.name} onChange={e => setBuilder({ ...builder, name: e.target.value })} /></Field>
            <Field label="슬러그"><input className="inp" value={builder.slug} onChange={e => setBuilder({ ...builder, slug: e.target.value })} /></Field>
          </div>
          <div className="flex items-center justify-between mb-2">
            <span className="text-sm font-semibold flex items-center gap-1.5"><ListChecks size={15} /> 필드 정의</span>
            <Btn size="sm" variant="ghost" onClick={addField}><Plus size={13} /> 필드</Btn>
          </div>
          <div className="space-y-2 max-h-72 overflow-auto">
            {builder.fields.map((f: any, i: number) => (
              <div key={i} className="grid grid-cols-12 gap-2 items-center bg-panel border border-edge rounded p-2">
                <input className="inp col-span-3" placeholder="name" value={f.name} onChange={e => setField(i, { name: e.target.value })} />
                <input className="inp col-span-3" placeholder="라벨" value={f.label} onChange={e => setField(i, { label: e.target.value })} />
                <select className="inp col-span-3" value={f.type} onChange={e => setField(i, { type: e.target.value })}>
                  {FIELD_TYPES.map(t => <option key={t}>{t}</option>)}
                </select>
                <label className="col-span-2 text-xs flex items-center gap-1 text-slate-400">
                  <input type="checkbox" checked={!!f.required} onChange={e => setField(i, { required: e.target.checked })} /> 필수
                </label>
                <button onClick={() => delField(i)} className="col-span-1 text-rose-400 hover:text-rose-300"><Trash2 size={14} /></button>
              </div>
            ))}
            {builder.fields.length === 0 && <div className="text-center text-slate-500 text-xs py-6 border border-dashed border-edge rounded">필드를 추가하세요.</div>}
          </div>
          <div className="flex justify-end gap-2 mt-5">
            <Btn variant="ghost" onClick={() => setBuilder(null)}>취소</Btn>
            <Btn onClick={save}>저장</Btn>
          </div>
        </Modal>
      )}

      {subFor && (
        <Modal title={`제출 내역 — ${subFor.name}`} onClose={() => setSubFor(null)} wide>
          <div className="flex items-center gap-2 mb-3">
            <label className="text-xs flex items-center gap-1 text-slate-400">
              <input type="checkbox" checked={includeSpam} onChange={e => openSubs(subFor, e.target.checked)} /> 스팸 포함
            </label>
          </div>
          {subs.length === 0 ? <p className="text-slate-500 text-sm">제출 내역이 없습니다.</p> : (
            <div className="space-y-2 max-h-[60vh] overflow-auto">
              {subs.map((s: any, i: number) => (
                <div key={s.id ?? i} className="bg-ink border border-edge rounded p-3 text-xs">
                  <div className="flex items-center justify-between mb-1">
                    <span className="text-slate-500">{s.createdAt ? new Date(s.createdAt).toLocaleString('ko-KR') : ''}</span>
                    {s.spam && <span className="text-rose-400">SPAM</span>}
                  </div>
                  <pre className="text-slate-300 whitespace-pre-wrap">{JSON.stringify(s.payload ?? s, null, 2)}</pre>
                </div>
              ))}
            </div>
          )}
        </Modal>
      )}
    </div>
  )
}

function safeFields(v: any): any[] {
  if (Array.isArray(v)) return v
  try { const p = JSON.parse(v); return Array.isArray(p) ? p : [] } catch { return [] }
}
