'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)
    }
  }

  return (
    <div>
      {/* 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="admin-form info-box-light separate2"
      >
        <span className="second-brown">{t('newCategory')}</span>
        <input value={catForm.name} onChange={(e) => setCatForm({ ...catForm, name: e.target.value })} placeholder={t('categoryName')} />
        <span className="second-brown">{t('order')}</span>
        <input type="number" value={catForm.order} onChange={(e) => setCatForm({ ...catForm, order: e.target.value })} />
        <button type="submit" disabled={busy}>{t('create')}</button>
      </form>
      <br />

      {initial.length === 0 && <p className="second-brown centered">{t('noCategories')}</p>}

      {initial.map(({ category, forums }) => (
        <div key={category.id} className="inline-div" style={{ display: 'block' }}>
          <div className="title-content-h3">
            <h3 className="big-font">
              {category.name} <span className="third-brown small-font">#{category.order}</span>{' '}
              <button
                onClick={() => confirm(t('confirmDelete')) && call(`/api/admin/forum/category/${category.id}`, 'DELETE')}
                disabled={busy}
                className="nw-tool-btn red-info2"
              >
                {t('delete')}
              </button>
            </h3>
          </div>

          {/* Foros de la categoría */}
          <table className="max-center-table">
            <tbody>
              {forums.length === 0 && (
                <tr>
                  <td className="second-brown centered">{t('noForums')}</td>
                </tr>
              )}
              {forums.map((f) => (
                <tr key={f.id} className="team-center-table-tr">
                  <td className="lefted separate">
                    <span className="yellow-info">{f.name}</span>{' '}
                    {f.visibility === 0 && <span className="red-info2 small-font">({t('hidden')})</span>}
                    {f.description && <p className="third-brown small-font">{f.description}</p>}
                  </td>
                  <td className="real-info-box no-wrap-td">
                    <button
                      onClick={() => call(`/api/admin/forum/${f.id}`, 'PATCH', { visibility: f.visibility === 0 })}
                      disabled={busy}
                      className="nw-tool-btn"
                    >
                      {f.visibility === 0 ? t('show') : t('hide')}
                    </button>{' '}
                    <button
                      onClick={() => confirm(t('confirmDelete')) && call(`/api/admin/forum/${f.id}`, 'DELETE')}
                      disabled={busy}
                      className="nw-tool-btn red-info2"
                    >
                      {t('delete')}
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>

          {/* 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="admin-form separate"
          >
            <input value={ff(category.id).name} onChange={(e) => setFF(category.id, { name: e.target.value })} placeholder={t('forumName')} maxLength={45} />
            <input value={ff(category.id).description} onChange={(e) => setFF(category.id, { description: e.target.value })} placeholder={t('forumDescription')} />
            <button type="submit" disabled={busy}>{t('addForum')}</button>
          </form>
        </div>
      ))}
    </div>
  )
}
