'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { PrimaryButton, TextareaField } from '@/app/FormFields'
import { useI18n } from '@/lib/i18n/client'

interface Props {
  ticketId: string
  context?: 'awaiting_reply' | 'follow_up'
}

export default function FollowUpForm({ ticketId, context = 'awaiting_reply' }: Props) {
  const { t } = useI18n()
  const router = useRouter()
  const [text, setText] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const headingKey = context === 'awaiting_reply'
    ? 'ticketDetail.followUpForm.awaitingReplyHeading'
    : 'ticketDetail.followUpForm.followUpHeading'
  const bodyKey = context === 'awaiting_reply'
    ? 'ticketDetail.followUpForm.awaitingReplyBody'
    : 'ticketDetail.followUpForm.followUpBody'
  const placeholderKey = context === 'awaiting_reply'
    ? 'ticketDetail.followUpForm.awaitingReplyPlaceholder'
    : 'ticketDetail.followUpForm.followUpPlaceholder'
  const buttonKey = context === 'awaiting_reply'
    ? 'ticketDetail.followUpForm.awaitingReplyButton'
    : 'ticketDetail.followUpForm.followUpButton'

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    const trimmed = text.trim()
    if (trimmed.length < 5) {
      setError(t('ticketDetail.followUpForm.minWords'))
      return
    }
    setLoading(true)
    setError(null)
    try {
      const res = await fetch(`/api/tickets/${ticketId}/messages`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ submissionText: trimmed }),
      })
      if (!res.ok) {
        const data = await res.json().catch(() => ({}))
        setError((data as { error?: string }).error ?? t('ticketDetail.followUpForm.replyError'))
        return
      }
      setText('')
      router.refresh()
    } catch {
      setError(t('ticketDetail.followUpForm.generic'))
    } finally {
      setLoading(false)
    }
  }

  return (
    <section className="rounded-lg border border-sky-200 bg-sky-50 p-5 dark:border-sky-400/30 dark:bg-sky-400/10">
      <h2 className="mb-1 text-sm font-semibold text-sky-950 dark:text-sky-100">
        {t(headingKey)}
      </h2>
      <p className="mb-4 text-sm text-sky-800 dark:text-sky-200">
        {t(bodyKey)}
      </p>
      <form onSubmit={handleSubmit} className="space-y-3">
        <TextareaField
          value={text}
          onChange={(e) => setText(e.target.value)}
          rows={4}
          required
          placeholder={t(placeholderKey)}
          className="border-sky-300 focus:border-sky-700 focus:ring-sky-700/20 dark:border-sky-500/40"
        />
        {error ? <p className="text-sm text-red-700 dark:text-red-300">{error}</p> : null}
        <PrimaryButton
          type="submit"
          loading={loading}
          disabled={text.trim().length < 5}
        >
          {loading ? t('ticketDetail.followUpForm.sending') : t(buttonKey)}
        </PrimaryButton>
      </form>
    </section>
  )
}
