'use client'

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

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 handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (busy || !text.trim()) 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 } = await res.json()
      if (data.success) {
        setText('')
        router.refresh()
      } else {
        setError(t('genericError'))
      }
    } catch {
      setError(t('genericError'))
    } finally {
      setBusy(false)
    }
  }

  return (
    <form onSubmit={handleSubmit} className="separate2">
      <RichTextArea value={text} onChange={setText} placeholder={t('replyText')} rows={3} />
      <br />
      <button type="submit" disabled={busy}>
        {busy ? t('sending') : t('sendReply')}
      </button>
      <div className="alert-message" style={{ display: error ? 'block' : 'none' }}>
        {error && <span className="red-form-response">{error}</span>}
      </div>
    </form>
  )
}
