import { useEffect, useState } from 'react'
import { Palette, Plus, Trash2, Check, Edit3 } from 'lucide-react'
import StatusBadge from '../components/StatusBadge'
import { PageHeader, Btn, Field, Modal, Empty, jsonStr, safeJson } from '../components/ui'
import { canWrite } from '../components/rbac'
import { getThemes, createTheme, updateTheme, activateTheme, deleteTheme } from '../api/client'

const emptyForm = { name: '', layout: '{\n  "slots": ["header", "main", "footer"]\n}', tokens: '{\n  "brand": "#00a0c8"\n}', active: false }

export default function Themes() {
  const [list, setList] = useState<any[]>([])
  const [form, setForm] = useState<any>(null)
  const writable = canWrite()

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

  const openNew = () => setForm({ ...emptyForm })
  const openEdit = (t: any) => setForm({ ...t, layout: jsonStr(t.layout), tokens: jsonStr(t.tokens) })
  const save = async () => {
    const payload = { ...form, layout: safeJson(form.layout, {}), tokens: safeJson(form.tokens, {}) }
    if (form.id) await updateTheme(form.id, payload); else await createTheme(payload)
    setForm(null); load()
  }
  const activate = async (id: number) => { await activateTheme(id); load() }
  const remove = async (id: number) => { if (!window.confirm('삭제하시겠습니까?')) return; await deleteTheme(id); load() }

  return (
    <div>
      <PageHeader title="테마 / 템플릿" subtitle="레이아웃 슬롯 · 디자인 토큰 · 단일 활성"
        actions={writable && <Btn onClick={openNew}><Plus size={16} /> 테마 추가</Btn>} />

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {list.map(t => {
          const tokens = safeJson(t.tokens, {})
          return (
            <div key={t.id} className={`bg-card border rounded-xl p-4 ${t.active ? 'border-brand' : 'border-edge'}`}>
              <div className="flex items-center justify-between mb-2">
                <span className="font-medium flex items-center gap-1.5"><Palette size={15} className="text-brand" /> {t.name}</span>
                <StatusBadge status={t.active ? 'ACTIVE' : 'INACTIVE'} />
              </div>
              <div className="flex gap-1.5 mb-3">
                {Object.values(tokens).slice(0, 6).map((v: any, i) => typeof v === 'string' && v.startsWith('#') &&
                  <span key={i} className="w-6 h-6 rounded border border-edge" style={{ background: v }} title={v} />)}
              </div>
              {writable && (
                <div className="flex items-center gap-3">
                  {!t.active && <button onClick={() => activate(t.id)} title="활성화" className="text-emerald-400 hover:text-emerald-300"><Check size={15} /></button>}
                  <button onClick={() => openEdit(t)} className="text-slate-400 hover:text-brand"><Edit3 size={14} /></button>
                  <button onClick={() => remove(t.id)} className="text-rose-400 hover:text-rose-300"><Trash2 size={14} /></button>
                </div>
              )}
            </div>
          )
        })}
        {list.length === 0 && <div className="col-span-3"><Empty msg="테마가 없습니다." /></div>}
      </div>

      {form && (
        <Modal title={form.id ? '테마 편집' : '테마 추가'} onClose={() => setForm(null)} wide>
          <div className="space-y-3">
            <Field label="이름"><input className="inp" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} /></Field>
            <div className="grid grid-cols-2 gap-3">
              <Field label="레이아웃 (JSON)"><textarea className="inp font-mono text-xs" style={{ minHeight: 140 }} value={form.layout} onChange={e => setForm({ ...form, layout: e.target.value })} /></Field>
              <Field label="토큰 (JSON)"><textarea className="inp font-mono text-xs" style={{ minHeight: 140 }} value={form.tokens} onChange={e => setForm({ ...form, tokens: e.target.value })} /></Field>
            </div>
          </div>
          <div className="flex justify-end gap-2 mt-5">
            <Btn variant="ghost" onClick={() => setForm(null)}>취소</Btn>
            <Btn onClick={save}>저장</Btn>
          </div>
        </Modal>
      )}
    </div>
  )
}
