'use client'

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

/** Respuesta rápida a un tema: editor TinyMCE, enviado por fetch. */
export function ReplyForm({ topicId }: { topicId: number }) {
  const t = useTranslations('Forum')
  const router = useRouter()
  const [text, setText] = useState('')
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState<string | null>(null)

  async function submit(e: React.FormEvent) {
    e.preventDefault()
    if (busy) return
    setBusy(true)
    setError(null)
    try {
      const res = await fetch('/api/forum/reply', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({ topicId, text }),
      })
      const data: { success?: boolean; error?: string } = await res.json()
      if (data.success) {
        setText('')
        router.refresh()
      } else {
        setError(data.error || t('genericError'))
      }
    } catch {
      setError(t('genericError'))
    } finally {
      setBusy(false)
    }
  }

  return (
    <div className="quick_reply">
      <h2>{t('reply')}</h2>
      <form onSubmit={submit}>
        <ForumEditor value={text} onChange={setText} height={260} />
        <div className="forum-form-actions">
          <button type="submit" className="nice_button" disabled={busy}>
            {busy ? t('sending') : t('post')}
          </button>
          {error && <span className="red-form-response">{error}</span>}
        </div>
      </form>
    </div>
  )
}
