'use client'

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

interface Props {
  characters: CharOption[]
  checkoutEndpoint: string
  payLabel: string // ya formateado con el precio
  buttonClass?: string
  provider?: 'stripe' | 'sumup' // pasarela; por defecto Stripe
  confirmText?: string // si se pasa, pide confirmación antes de redirigir al pago
}

/** Selector de personaje + botón de pago. Redirige al Checkout (Stripe o SumUp). */
export function PaidServiceForm({ characters, checkoutEndpoint, payLabel, buttonClass = '', provider, confirmText }: Props) {
  const t = useTranslations('Services')
  const [character, setCharacter] = useState('')
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState<string | null>(null)

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (busy || !character) return
    if (confirmText && !window.confirm(confirmText)) return
    setBusy(true)
    setError(null)
    try {
      const res = await fetch(checkoutEndpoint, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({ character, ...(provider ? { provider } : {}) }),
      })
      const data: { success?: boolean; url?: string; message?: string } = await res.json()
      if (data.success && data.url) {
        window.location.href = data.url // Checkout (Stripe o SumUp)
      } else {
        setError(data.message || t('genericError'))
        setBusy(false)
      }
    } catch {
      setError(t('genericError'))
      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">
        <CharacterSelect characters={characters} value={character} onChange={setCharacter} placeholder={t('selectCharacter')} />
        <br />
        <button type="submit" className={buttonClass} disabled={busy || !character}>
          {busy ? t('processing') : payLabel}
        </button>
      </form>
      <hr />
      <div className="alert-message" style={{ display: error ? 'block' : 'none' }}>
        {error && <span className="red-form-response">{error}</span>}
      </div>
    </div>
  )
}
