'use client'

import { useEffect, useState } from 'react'
import { Plus } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendNewsCategory } from '@/lib/backend'

function emptyCategory(): BackendNewsCategory {
  return { code: '', name: '', description: '', sortOrder: 100, status: 'active', articleCount: 0 }
}

export default function AdminNewsCategoriesPage() {
  const [items, setItems] = useState<BackendNewsCategory[]>([])
  const [draft, setDraft] = useState<BackendNewsCategory>(emptyCategory())
  const [error, setError] = useState('')
  const [saving, setSaving] = useState('')

  async function load() {
    try {
      const result = await backend.adminNewsCategories()
      setItems(result.items)
    } catch (err) {
      setError(err instanceof Error ? err.message : '资讯分类加载失败')
    }
  }

  useEffect(() => {
    void load()
  }, [])

  async function saveCategory(item: BackendNewsCategory) {
    setSaving(item.code || 'new')
    setError('')
    try {
      if (item.code && items.some((current) => current.code === item.code)) {
        await backend.updateAdminNewsCategory(item.code, item)
      } else {
        await backend.createAdminNewsCategory(item)
        setDraft(emptyCategory())
      }
      await load()
    } catch (err) {
      setError(err instanceof Error ? err.message : '保存资讯分类失败')
    } finally {
      setSaving('')
    }
  }

  async function disableCategory(code: string) {
    setSaving(code)
    setError('')
    try {
      await backend.deleteAdminNewsCategory(code)
      await load()
    } catch (err) {
      setError(err instanceof Error ? err.message : '禁用资讯分类失败')
    } finally {
      setSaving('')
    }
  }

  const rows = [...items].sort((a, b) => a.sortOrder - b.sortOrder)

  return (
    <AdminShell title="资讯分类" description="维护新闻资讯左侧栏目、发文分类和前台筛选顺序。">
      <div className="space-y-4">
        {error && <div className="border border-red-100 bg-red-50 px-4 py-3 text-sm font-bold text-red-700">{error}</div>}

        <section className="border border-line bg-white">
          <div className="border-b border-line px-4 py-3 text-sm font-extrabold text-ink">新增分类</div>
          <div className="grid gap-3 px-4 py-4 md:grid-cols-[160px_180px_1fr_90px_110px_auto] md:items-center">
            <input value={draft.code} onChange={(event) => setDraft((current) => ({ ...current, code: event.target.value.trim() }))} placeholder="category_code" className="h-9 rounded-[4px] border border-line px-3 text-sm" />
            <input value={draft.name} onChange={(event) => setDraft((current) => ({ ...current, name: event.target.value }))} placeholder="分类名称" className="h-9 rounded-[4px] border border-line px-3 text-sm" />
            <input value={draft.description} onChange={(event) => setDraft((current) => ({ ...current, description: event.target.value }))} placeholder="说明" className="h-9 rounded-[4px] border border-line px-3 text-sm" />
            <input value={draft.sortOrder} type="number" onChange={(event) => setDraft((current) => ({ ...current, sortOrder: Number(event.target.value || 0) }))} className="h-9 rounded-[4px] border border-line px-3 text-sm" />
            <select value={draft.status} onChange={(event) => setDraft((current) => ({ ...current, status: event.target.value as BackendNewsCategory['status'] }))} className="h-9 rounded-[4px] border border-line px-2 text-sm">
              <option value="active">启用</option>
              <option value="disabled">禁用</option>
            </select>
            <button type="button" onClick={() => saveCategory(draft)} disabled={saving === 'new'} className="inline-flex h-9 items-center gap-1.5 rounded-[4px] bg-brand px-4 text-xs font-extrabold text-white disabled:bg-line-dark">
              <Plus className="h-3.5 w-3.5" />
              新增
            </button>
          </div>
        </section>

        <section className="border border-line bg-white">
          <div className="grid grid-cols-[160px_180px_1fr_90px_90px_90px_120px] border-b border-line px-4 py-3 text-xs font-extrabold text-soft">
            <span>分类码</span><span>名称</span><span>说明</span><span>排序</span><span>状态</span><span>文章数</span><span>操作</span>
          </div>
          <div className="divide-y divide-line">
            {rows.map((item) => (
              <div key={item.code} className="grid gap-3 px-4 py-3 md:grid-cols-[160px_180px_1fr_90px_90px_90px_120px] md:items-center">
                <input value={item.code} readOnly className="h-9 rounded-[4px] border border-line bg-bg px-3 text-sm text-muted" />
                <input value={item.name} onChange={(event) => setItems((current) => current.map((row) => row.code === item.code ? { ...row, name: event.target.value } : row))} className="h-9 rounded-[4px] border border-line px-3 text-sm" />
                <input value={item.description} onChange={(event) => setItems((current) => current.map((row) => row.code === item.code ? { ...row, description: event.target.value } : row))} className="h-9 rounded-[4px] border border-line px-3 text-sm" />
                <input value={item.sortOrder} type="number" onChange={(event) => setItems((current) => current.map((row) => row.code === item.code ? { ...row, sortOrder: Number(event.target.value || 0) } : row))} className="h-9 rounded-[4px] border border-line px-3 text-sm" />
                <select value={item.status} onChange={(event) => setItems((current) => current.map((row) => row.code === item.code ? { ...row, status: event.target.value as BackendNewsCategory['status'] } : row))} className="h-9 rounded-[4px] border border-line px-2 text-sm">
                  <option value="active">启用</option>
                  <option value="disabled">禁用</option>
                </select>
                <div className="text-sm font-bold text-muted">{item.articleCount || 0}</div>
                <div className="flex gap-2">
                  <button type="button" onClick={() => saveCategory(item)} disabled={saving === item.code} className="h-8 rounded-[4px] border border-line px-3 text-xs font-extrabold text-ink hover:border-brand hover:text-brand">保存</button>
                  <button type="button" onClick={() => disableCategory(item.code)} disabled={saving === item.code || item.status === 'disabled'} className="h-8 rounded-[4px] border border-red-100 px-3 text-xs font-extrabold text-red-600 disabled:text-soft">禁用</button>
                </div>
              </div>
            ))}
          </div>
        </section>
      </div>
    </AdminShell>
  )
}
