'use client'

import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { useRouter } from '@/i18n/navigation'
import { CharacterSelect, type CharOption } from '@/components/CharacterSelect'

const ERROR_KEYS = ['noCharacter', 'notOfflineOrOwned', 'cooldown', 'soapError'] as const

interface Props {
  characters: CharOption[]
  endpoint: string
  actionLabel: string
  buttonClass?: string
  processingLabel?: string // texto mientras procesa (por defecto t('processing'))
  doneLabel?: string // si se pasa, muestra el estado "hecho" (dorado) y refresca a los 5s
  promptText?: string // texto encima del selector (por defecto t('choose'))
}

/** Formulario reutilizable para acciones de personaje por SOAP (revive, unstuck...). */
export function CharacterActionForm({
  characters,
  endpoint,
  actionLabel,
  buttonClass = '',
  processingLabel,
  doneLabel,
  promptText,
}: Props) {
  const t = useTranslations('Services')
  const router = useRouter()
  const [character, setCharacter] = useState('')
  const [busy, setBusy] = useState(false)
  const [done, setDone] = useState(false)
  const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null)

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (busy || done || !character) return
    setBusy(true)
    setMessage(null)
    try {
      const res = await fetch(endpoint, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({ character }),
      })
      const data: { success?: boolean; error?: string } = await res.json()
      if (data.success) {
        setMessage({ ok: true, text: t('success') })
        if (doneLabel) {
          // Como el original: tras 5 s se limpia el formulario y se refresca.
          setDone(true)
          setTimeout(() => {
            setDone(false)
            setCharacter('')
            setMessage(null)
            router.refresh()
          }, 5000)
        }
      } else {
        const key = (ERROR_KEYS as readonly string[]).includes(data.error ?? '') ? data.error! : 'genericError'
        setMessage({ ok: false, text: t(key) })
        setTimeout(() => setMessage(null), 5000)
      }
    } catch {
      setMessage({ ok: false, text: t('genericError') })
    } finally {
      setBusy(false)
    }
  }

  if (characters.length === 0) {
    return <p className="second-brown">{t('noCharactersYet')}</p>
  }

  return (
    <div className="centered">
      <br />
      <br />
      <p>{promptText ?? t('choose')}</p>
      <br />
      <form onSubmit={handleSubmit} acceptCharset="utf-8">
        <CharacterSelect characters={characters} value={character} onChange={setCharacter} placeholder={t('selectCharacter')} />
        <br />
        <button
          type="submit"
          className={buttonClass}
          disabled={busy || done || !character}
          style={done ? { color: '#d79602' } : undefined}
        >
          {done && doneLabel ? doneLabel : busy ? processingLabel ?? t('processing') : actionLabel}
        </button>
      </form>
      <hr />
      <div className="alert-message" style={{ display: message ? 'block' : 'none' }}>
        {message && <span className={message.ok ? 'ok-form-response' : 'red-form-response'}>{message.text}</span>}
      </div>
    </div>
  )
}
