'use client'

import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { useRouter } from '@/i18n/navigation'

/**
 * Acciones de moderación de un post o tema (borrar/restaurar y, en temas,
 * cerrar/abrir). Reemplaza los enlaces GET del forum.js original por POST a
 * /api/forum/moderate, para no mutar estado con peticiones GET.
 */
export function ForumModActions({
  kind,
  id,
  deleted = false,
  locked = false,
}: {
  kind: 'post' | 'topic'
  id: number
  deleted?: boolean
  locked?: boolean
}) {
  const t = useTranslations('Forum')
  const router = useRouter()
  const [busy, setBusy] = useState(false)

  async function act(action: string) {
    if (busy) return
    setBusy(true)
    try {
      const res = await fetch('/api/forum/moderate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({ kind, id, action }),
      })
      const data: { success?: boolean } = await res.json()
      if (data.success) router.refresh()
    } finally {
      setBusy(false)
    }
  }

  return (
    <>
      <a
        className="delete"
        role="button"
        tabIndex={0}
        onClick={() => act(deleted ? 'undelete' : 'delete')}
        style={busy ? { opacity: 0.5 } : undefined}
      >
        {deleted ? t('undelete') : t('delete')}
      </a>
      {kind === 'topic' && (
        <a
          className="lock"
          role="button"
          tabIndex={0}
          onClick={() => act(locked ? 'unlock' : 'lock')}
          style={busy ? { opacity: 0.5 } : undefined}
        >
          {locked ? t('unlock') : t('lock')}
        </a>
      )}
    </>
  )
}
