'use client'

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

/** Formulario de nuevo tema: título + editor TinyMCE, enviado por fetch. */
export function CreateTopicForm({ forumId }: { forumId: number }) {
  const t = useTranslations('Forum')
  const router = useRouter()
  const [title, setTitle] = useState('')
  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
    if (title.trim().length < 3) return setError(t('errTitle'))
    setBusy(true)
    setError(null)
    try {
      const res = await fetch('/api/forum/topic', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({ forumId, title, text }),
      })
      const data: { success?: boolean; topicId?: number; error?: string } = await res.json()
      if (data.success && data.topicId) router.push(`/forum/topic/${data.topicId}`)
      else setError(data.error || t('genericError'))
    } catch {
      setError(t('genericError'))
    } finally {
      setBusy(false)
    }
  }

  return (
    <form onSubmit={submit}>
      <input
        className="forum-input"
        value={title}
        onChange={(e) => setTitle(e.target.value)}
        type="text"
        placeholder={t('topicTitle')}
        maxLength={45}
      />
      <ForumEditor value={text} onChange={setText} />
      <div className="forum-form-actions">
        <button type="submit" className="nice_button" disabled={busy}>
          {busy ? t('sending') : t('postTopic')}
        </button>
        {error && <span className="red-form-response">{error}</span>}
      </div>
    </form>
  )
}
