'use client'

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

interface Props {
  characters: CharOption[]
  checkoutEndpoint: string
  payLabel: string // texto de acción del botón
  priceEur: number // precio del servicio en euros (para calcular el coste en PD)
  pdBalance: number // saldo PD de la cuenta
  buttonClass?: string
}

/** Selector de personaje + forma de pago (PD / Stripe / SumUp) + botón. */
export function PaidServiceForm({ characters, checkoutEndpoint, payLabel, priceEur, pdBalance, buttonClass = '' }: Props) {
  const t = useTranslations('Services')
  const tp = useTranslations('Pay')
  const locale = useLocale()
  const [character, setCharacter] = useState('')
  const [method, setMethod] = useState<PayMethod>(pdBalance >= pdCostOf(priceEur) ? 'pd' : 'sumup')
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState<string | null>(null)

  function msgFor(err?: string): string {
    return err && tp.has(`errors.${err}`) ? tp(`errors.${err}`) : t('genericError')
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (busy || !character) return
    const amount = method === 'pd' ? tp('pdCost', { cost: pdCostOf(priceEur) }) : tp('eur', { price: priceEur })
    if (!window.confirm(tp('confirm', { amount }))) 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: method, locale }),
      })
      const data: { success?: boolean; url?: string; message?: string; error?: string } = await res.json()
      if (data.success && data.url) {
        window.location.href = data.url // éxito PD, o Checkout (Stripe/SumUp)
      } else {
        setError(data.message || msgFor(data.error))
        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" noValidate>
        <CharacterSelect characters={characters} value={character} onChange={setCharacter} placeholder={t('selectCharacter')} />
        <PaymentMethodSelect value={method} onChange={setMethod} priceEur={priceEur} pdBalance={pdBalance} />
        <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>
  )
}
