'use client'

import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { useRouter } from '@/i18n/navigation'
import type { AdminCategory, AdminForum } from '@/lib/admin-forum'

type Group = { category: AdminCategory; forums: AdminForum[] }

export function AdminForumManager({ initial }: { initial: Group[] }) {
  const t = useTranslations('Admin')
  const router = useRouter()
  const [busy, setBusy] = useState(false)
  const [catForm, setCatForm] = useState({ name: '', order: '0' })
  const [forumForm, setForumForm] = useState<Record<number, { name: string; description: string; order: string }>>({})

  function ff(catId: number) {
    return forumForm[catId] ?? { name: '', description: '', order: '0' }
  }
  function setFF(catId: number, patch: Partial<{ name: string; description: string; order: string }>) {
    setForumForm((s) => ({ ...s, [catId]: { ...ff(catId), ...patch } }))
  }

  async function call(url: string, method: string, body?: unknown): Promise<boolean> {
    setBusy(true)
    try {
      const res = await fetch(url, {
        method,
        headers: body ? { 'Content-Type': 'application/json' } : undefined,
        credentials: 'same-origin',
        body: body ? JSON.stringify(body) : undefined,
      })
      const d = await res.json()
      if (d.success) {
        router.refresh()
        return true
      }
      if (d.error === 'categoryNotEmpty') alert(t('categoryNotEmpty'))
      return false
    } finally {
      setBusy(false)
    }
  }

  const field = 'nw-input'
  return (
    <div className="space-y-6">
      {/* Alta de categoría */}
      <form
        onSubmit={(e) => {
          e.preventDefault()
          if (catForm.name.trim()) call('/api/admin/forum/category', 'POST', { name: catForm.name, order: Number(catForm.order) }).then((ok) => ok && setCatForm({ name: '', order: '0' }))
        }}
        className="flex flex-wrap items-end gap-2 nw-card"
      >
        <label className="flex-1 text-sm">
          <span className="mb-1 block text-nw-muted">{t('newCategory')}</span>
          <input value={catForm.name} onChange={(e) => setCatForm({ ...catForm, name: e.target.value })} placeholder={t('categoryName')} className={field} />
        </label>
        <label className="w-20 text-sm">
          <span className="mb-1 block text-nw-muted">{t('order')}</span>
          <input type="number" value={catForm.order} onChange={(e) => setCatForm({ ...catForm, order: e.target.value })} className={field} />
        </label>
        <button type="submit" disabled={busy} className="nw-btn disabled:opacity-60">{t('create')}</button>
      </form>

      {initial.length === 0 && <p className="text-amber-200/70">{t('noCategories')}</p>}

      {initial.map(({ category, forums }) => (
        <section key={category.id} className="nw-card">
          <div className="mb-3 flex items-center justify-between gap-2">
            <h2 className="text-lg font-semibold text-nw-gold-light">
              {category.name} <span className="text-xs text-nw-muted">#{category.order}</span>
            </h2>
            <button
              onClick={() => confirm(t('confirmDelete')) && call(`/api/admin/forum/category/${category.id}`, 'DELETE')}
              disabled={busy}
              className="rounded border border-red-900/60 px-2 py-1 text-xs text-red-400 hover:bg-red-950/40 disabled:opacity-60"
            >
              {t('delete')}
            </button>
          </div>

          {/* Foros de la categoría */}
          <ul className="mb-3 divide-y divide-amber-900/40">
            {forums.length === 0 && <li className="py-2 text-sm text-nw-muted">{t('noForums')}</li>}
            {forums.map((f) => (
              <li key={f.id} className="flex items-center justify-between gap-3 py-2">
                <div className="min-w-0">
                  <p className="font-medium text-amber-300">
                    {f.name} {f.visibility === 0 && <span className="text-xs text-red-400">({t('hidden')})</span>}
                  </p>
                  {f.description && <p className="truncate text-xs text-nw-muted">{f.description}</p>}
                </div>
                <div className="flex shrink-0 items-center gap-2">
                  <button
                    onClick={() => call(`/api/admin/forum/${f.id}`, 'PATCH', { visibility: f.visibility === 0 })}
                    disabled={busy}
                    className="nw-btn-ghost text-xs disabled:opacity-60"
                  >
                    {f.visibility === 0 ? t('show') : t('hide')}
                  </button>
                  <button
                    onClick={() => confirm(t('confirmDelete')) && call(`/api/admin/forum/${f.id}`, 'DELETE')}
                    disabled={busy}
                    className="rounded border border-red-900/60 px-2 py-1 text-xs text-red-400 hover:bg-red-950/40 disabled:opacity-60"
                  >
                    {t('delete')}
                  </button>
                </div>
              </li>
            ))}
          </ul>

          {/* Alta de foro en esta categoría */}
          <form
            onSubmit={(e) => {
              e.preventDefault()
              const v = ff(category.id)
              if (v.name.trim())
                call('/api/admin/forum', 'POST', { categoryId: category.id, name: v.name, description: v.description, order: Number(v.order) }).then(
                  (ok) => ok && setFF(category.id, { name: '', description: '', order: '0' }),
                )
            }}
            className="grid gap-2 rounded-lg border border-nw-border/50 bg-nw-panel-2/30 p-3 sm:grid-cols-[1fr_1fr_auto]"
          >
            <input value={ff(category.id).name} onChange={(e) => setFF(category.id, { name: e.target.value })} placeholder={t('forumName')} maxLength={45} className={field} />
            <input value={ff(category.id).description} onChange={(e) => setFF(category.id, { description: e.target.value })} placeholder={t('forumDescription')} className={field} />
            <button type="submit" disabled={busy} className="nw-btn text-sm disabled:opacity-60">{t('addForum')}</button>
          </form>
        </section>
      ))}
    </div>
  )
}
