import { useEffect, useState } from 'react'
import { ListTree, Plus, Trash2, ChevronRight, ChevronDown, FileCode } from 'lucide-react'
import { PageHeader, Btn, Field, Modal, Empty } from '../components/ui'
import { canWrite } from '../components/rbac'
import { getMenuTree, getMenus, createMenu, updateMenu, deleteMenu, getSitemap } from '../api/client'

const MENU_TYPES = ['MAIN', 'FOOTER', 'CATEGORY', 'SIDEBAR']
const emptyForm = { parentId: null as number | null, name: '', menuType: 'MAIN', url: '', slug: '', sortOrder: 0, active: true }

export default function Menus() {
  const [menuType, setMenuType] = useState('MAIN')
  const [tree, setTree] = useState<any[]>([])
  const [flat, setFlat] = useState<any[]>([])
  const [form, setForm] = useState<any>(null)
  const [sitemap, setSitemap] = useState('')
  const writable = canWrite()

  const load = () => {
    getMenuTree(menuType).then(d => setTree(d || [])).catch(() => setTree([]))
    getMenus(menuType).then(d => setFlat(d || [])).catch(() => setFlat([]))
  }
  useEffect(() => { load() }, [menuType])

  const save = async () => {
    const payload = { ...form, menuType }
    if (form.id) await updateMenu(form.id, payload); else await createMenu(payload)
    setForm(null); load()
  }
  const remove = async (id: number) => {
    if (!window.confirm('삭제하시겠습니까? (하위 메뉴가 있으면 거부됩니다)')) return
    try { await deleteMenu(id); load() }
    catch (e: any) { window.alert(e?.response?.status === 409 ? '하위 메뉴가 있어 삭제할 수 없습니다.' : '삭제 실패') }
  }
  const showSitemap = async () => {
    const r = await getSitemap('https://example.com')
    setSitemap(r?.xml || '')
  }

  return (
    <div>
      <PageHeader title="메뉴 / 카테고리" subtitle="내비게이션 · 카테고리 트리 · 사이트맵"
        actions={
          <div className="flex gap-2">
            <Btn variant="ghost" onClick={showSitemap}><FileCode size={15} /> 사이트맵</Btn>
            {writable && <Btn onClick={() => setForm({ ...emptyForm })}><Plus size={16} /> 메뉴 추가</Btn>}
          </div>
        } />

      <div className="flex items-center gap-2 mb-4">
        <select className="inp w-44" value={menuType} onChange={e => setMenuType(e.target.value)}>
          {MENU_TYPES.map(t => <option key={t}>{t}</option>)}
        </select>
      </div>

      <div className="bg-card border border-edge rounded-xl p-4">
        {tree.length === 0 ? <p className="text-slate-500 text-sm py-4 text-center">메뉴가 없습니다.</p> :
          tree.map(node => <TreeNode key={node.id} node={node} depth={0} onEdit={(n: any) => setForm({ ...n })} onAddChild={(p: number) => setForm({ ...emptyForm, parentId: p })} onDel={remove} writable={writable} />)}
      </div>

      {form && (
        <Modal title={form.id ? '메뉴 편집' : '메뉴 추가'} onClose={() => setForm(null)}>
          <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="URL"><input className="inp" value={form.url || ''} onChange={e => setForm({ ...form, url: e.target.value })} /></Field>
              <Field label="슬러그"><input className="inp" value={form.slug || ''} onChange={e => setForm({ ...form, slug: e.target.value })} /></Field>
            </div>
            <div className="grid grid-cols-2 gap-3">
              <Field label="상위 메뉴">
                <select className="inp" value={form.parentId ?? ''} onChange={e => setForm({ ...form, parentId: e.target.value ? Number(e.target.value) : null })}>
                  <option value="">(최상위)</option>
                  {flat.filter(m => m.id !== form.id).map(m => <option key={m.id} value={m.id}>{m.name}</option>)}
                </select>
              </Field>
              <Field label="정렬 순서"><input className="inp" type="number" value={form.sortOrder} onChange={e => setForm({ ...form, sortOrder: Number(e.target.value) })} /></Field>
            </div>
            <Field label="활성">
              <select className="inp" value={String(form.active)} onChange={e => setForm({ ...form, active: e.target.value === 'true' })}>
                <option value="true">활성</option><option value="false">비활성</option>
              </select>
            </Field>
          </div>
          <div className="flex justify-end gap-2 mt-5">
            <Btn variant="ghost" onClick={() => setForm(null)}>취소</Btn>
            <Btn onClick={save}>저장</Btn>
          </div>
        </Modal>
      )}

      {sitemap && (
        <Modal title="sitemap.xml" onClose={() => setSitemap('')} wide>
          <pre className="text-[11px] text-slate-400 bg-ink border border-edge rounded p-3 overflow-auto max-h-[60vh]">{sitemap}</pre>
        </Modal>
      )}
    </div>
  )
}

function TreeNode({ node, depth, onEdit, onAddChild, onDel, writable }: any) {
  const [open, setOpen] = useState(true)
  const children = node.children || []
  return (
    <div>
      <div className="flex items-center gap-2 py-1.5 hover:bg-panel/40 rounded px-2" style={{ marginLeft: depth * 18 }}>
        {children.length > 0
          ? <button onClick={() => setOpen(!open)} className="text-slate-500">{open ? <ChevronDown size={14} /> : <ChevronRight size={14} />}</button>
          : <span className="w-3.5 inline-block" />}
        <ListTree size={14} className="text-brand" />
        <span className="text-sm font-medium">{node.name}</span>
        {node.url && <span className="text-[11px] text-slate-500 font-mono">{node.url}</span>}
        {!node.active && <span className="text-[10px] text-slate-500">(비활성)</span>}
        {writable && (
          <div className="flex items-center gap-2 ml-auto">
            <button onClick={() => onAddChild(node.id)} className="text-slate-500 hover:text-brand"><Plus size={13} /></button>
            <button onClick={() => onEdit(node)} className="text-slate-400 hover:text-brand text-xs">편집</button>
            <button onClick={() => onDel(node.id)} className="text-rose-400 hover:text-rose-300"><Trash2 size={13} /></button>
          </div>
        )}
      </div>
      {open && children.map((c: any) => (
        <TreeNode key={c.id} node={c} depth={depth + 1} onEdit={onEdit} onAddChild={onAddChild} onDel={onDel} writable={writable} />
      ))}
    </div>
  )
}
