'use client'

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

export function GoldForm({ characters, options, pdBalance }: { characters: CharOption[]; options: GoldOption[]; pdBalance: number }) {
  const t = useTranslations('Services')
  const tp = useTranslations('Paid')
  const tpay = useTranslations('Pay')
  const locale = useLocale()
  const [character, setCharacter] = useState('')
  const [amount, setAmount] = useState('')
  const [method, setMethod] = useState<PayMethod>('pd')
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const price = options.find((o) => String(o.gold_amount) === amount)?.price ?? 0

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (busy || !character || !amount) return
    const payAmount = method === 'pd' ? tpay('pdCost', { cost: pdCostOf(price) }) : tpay('eur', { price })
    if (!window.confirm(tpay('confirm', { amount: payAmount }))) return
    setBusy(true)
    setError(null)
    try {
      const res = await fetch('/api/character/gold/checkout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({ character, gold_amount: amount, 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
      else {
        setError(data.message || (data.error && tpay.has(`errors.${data.error}`) ? tpay(`errors.${data.error}`) : 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">
      <form noValidate onSubmit={handleSubmit} acceptCharset="utf-8">
        <CharacterSelect characters={characters} value={character} onChange={setCharacter} placeholder={t('selectCharacter')} />
        <br />
        <select value={amount} onChange={(e) => setAmount(e.target.value)} required>
          <option value="" disabled>{tp('gold.selectAmount')}</option>
          {options.map((o) => (
            <option key={o.gold_amount} value={o.gold_amount}>
              {tp('gold.option', { amount: o.gold_amount, price: o.price })}
            </option>
          ))}
        </select>
        {amount && <PaymentMethodSelect value={method} onChange={setMethod} priceEur={price} pdBalance={pdBalance} />}
        <br />
        <button type="submit" className="gold-button" disabled={busy || !character || !amount}>
          {busy ? t('processing') : tp('gold.send')}
        </button>
      </form>
      <hr />
      <div className="alert-message" style={{ display: error ? 'block' : 'none' }}>
        {error && <span className="red-form-response">{error}</span>}
      </div>
    </div>
  )
}
