'use client'

import { useState } from 'react'
import { useTranslations } from 'next-intl'

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

interface Props {
  characters: string[]
  endpoint: string
  actionLabel: string
  buttonClass?: string
}

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

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (busy || !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') })
      else {
        const key = (ERROR_KEYS as readonly string[]).includes(data.error ?? '') ? data.error! : 'genericError'
        setMessage({ ok: false, text: t(key) })
      }
    } 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">
      <p>{t('choose')}</p>
      <br />
      <form onSubmit={handleSubmit} acceptCharset="utf-8">
        <select value={character} onChange={(e) => setCharacter(e.target.value)} required>
          <option value="" disabled>
            {t('selectCharacter')}
          </option>
          {characters.map((c) => (
            <option key={c} value={c}>
              {c}
            </option>
          ))}
        </select>
        <br />
        <button type="submit" className={buttonClass} disabled={busy || !character}>
          {busy ? 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>
  )
}
