'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
}

/** Formulario reutilizable para acciones de personaje por SOAP (revive, unstuck...). */
export function CharacterActionForm({ characters, endpoint, actionLabel }: 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="text-amber-200/70">{t('noCharactersYet')}</p>
  }

  return (
    <div className="mx-auto max-w-sm text-center">
      <form onSubmit={handleSubmit} className="space-y-3">
        <select
          value={character}
          onChange={(e) => setCharacter(e.target.value)}
          required
          className="nw-input"
        >
          <option value="" disabled>
            {t('selectCharacter')}
          </option>
          {characters.map((c) => (
            <option key={c} value={c}>
              {c}
            </option>
          ))}
        </select>
        <button
          type="submit"
          disabled={busy || !character}
          className="w-full nw-btn disabled:opacity-60"
        >
          {busy ? t('processing') : actionLabel}
        </button>
      </form>
      {message && <p className={`mt-3 ${message.ok ? 'text-green-400' : 'text-red-400'}`}>{message.text}</p>}
    </div>
  )
}
