'use client'

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

export function NewTopicForm({ forumId }: { forumId: number }) {
  const t = useTranslations('Forum')
  const router = useRouter()
  const [name, setName] = useState('')
  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 || !name.trim() || !text.trim()) return
    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, name, text }),
      })
      const data: { success?: boolean; topicId?: number } = await res.json()
      if (data.success && data.topicId) router.push(`/forum/topic/${data.topicId}`)
      else {
        setError(t('genericError'))
        setBusy(false)
      }
    } catch {
      setError(t('genericError'))
      setBusy(false)
    }
  }

  return (
    <form onSubmit={handleSubmit} className="info-box-light separate2">
      <div className="title-content-h3">
        <h3 className="big-font">{t('newTopic')}</h3>
      </div>
      <br />
      <input value={name} onChange={(e) => setName(e.target.value)} placeholder={t('newTopicName')} maxLength={200} style={{ width: '100%' }} />
      <br />
      <br />
      <RichTextArea value={text} onChange={setText} placeholder={t('newTopicText')} rows={4} />
      <br />
      <button type="submit" disabled={busy}>
        {busy ? t('publishing') : t('publish')}
      </button>
      <div className="alert-message" style={{ display: error ? 'block' : 'none' }}>
        {error && <span className="red-form-response">{error}</span>}
      </div>
    </form>
  )
}
