'use client'

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

/** Edición de un post a página completa: editor TinyMCE precargado, PATCH por fetch. */
export function EditPostPageForm({
  postId,
  topicId,
  initialText,
}: {
  postId: number
  topicId: number
  initialText: string
}) {
  const t = useTranslations('Forum')
  const router = useRouter()
  const [text, setText] = useState(initialText)
  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/post', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({ postId, text }),
      })
      const data: { success?: boolean; error?: string } = await res.json()
      if (data.success) router.push(`/forum/topic/${topicId}`)
      else setError(data.error || t('genericError'))
    } catch {
      setError(t('genericError'))
    } finally {
      setBusy(false)
    }
  }

  return (
    <form onSubmit={submit}>
      <ForumEditor value={text} onChange={setText} />
      <div className="forum-form-actions">
        <button type="submit" className="nice_button" disabled={busy}>
          {busy ? t('sending') : t('editPost')}
        </button>
        <Link className="nice_button" href={`/forum/topic/${topicId}`}>
          {t('cancel')}
        </Link>
        {error && <span className="red-form-response">{error}</span>}
      </div>
    </form>
  )
}
