'use client'

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

function renameErrorKey(error?: string): string {
  switch (error) {
    case 'missingFields':
    case 'invalidName':
    case 'invalidToken':
    case 'notGuildMaster':
    case 'nameTaken':
    case 'soapError':
    case 'notAuthenticated':
      return error
    case 'insufficientPd': // pago con PD sin saldo -> mensaje específico de hermandad
      return 'insufficientPoints'
    case 'fulfillFailed': // el renombrado por SOAP no se aplicó (se reembolsó)
      return 'soapError'
    default:
      return 'generic'
  }
}

export function RenameGuildForm({ guilds, price, pdBalance }: { guilds: GmGuild[]; price: number; pdBalance: number }) {
  const t = useTranslations('Points')
  const tpay = useTranslations('Pay')
  const locale = useLocale()
  const renameError = (error?: string) => t(`renameGuild.errors.${renameErrorKey(error)}`)
  const [guildId, setGuildId] = useState('')
  const [newName, setNewName] = useState('')
  const [token, setToken] = useState('')
  const [showToken, setShowToken] = useState(false)
  const [method, setMethod] = useState<PayMethod>(pdBalance >= pdCostOf(price) ? 'pd' : 'sumup')
  const [busy, setBusy] = useState(false)
  const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null)

  if (guilds.length === 0) {
    return (
      <div className="centered">
        <br />
        <span>{t('renameGuild.noGuilds')}</span>
        <br />
      </div>
    )
  }

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    if (busy) return
    if (!guildId || !newName.trim() || !token.trim()) {
      setMessage({ ok: false, text: renameError('missingFields') })
      return
    }
    const amount = method === 'pd' ? tpay('pdCost', { cost: pdCostOf(price) }) : tpay('eur', { price })
    if (!window.confirm(tpay('confirm', { amount }))) return

    setBusy(true)
    setMessage(null)
    try {
      const res = await fetch('/api/guild/rename/checkout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({ guildId: Number(guildId), newName: newName.trim(), token: token.trim(), provider: method, locale }),
      })
      const data: { success?: boolean; url?: string; error?: string } = await res.json()
      if (data.success && data.url) {
        window.location.href = data.url // éxito PD, o Checkout (Stripe/SumUp)
        return
      }
      setMessage({ ok: false, text: renameError(data.error) })
      setBusy(false)
    } catch {
      setMessage({ ok: false, text: renameError() })
      setBusy(false)
    }
  }

  return (
    <div className="centered">
      <form noValidate id="ns-rename-guild-form" onSubmit={handleSubmit} acceptCharset="utf-8">
        <table className="middle-center-table">
          <tbody>
            <tr>
              <td>
                <select value={guildId} onChange={(e) => setGuildId(e.target.value)} required>
                  <option value="" disabled>{t('renameGuild.selectGuild')}</option>
                  {guilds.map((g) => (
                    <option key={g.guildid} value={g.guildid}>{g.name}</option>
                  ))}
                </select>
              </td>
            </tr>
            <tr>
              <td>
                <input
                  type="text"
                  maxLength={24}
                  name="new-guild-name"
                  placeholder={t('renameGuild.newNamePlaceholder')}
                  value={newName}
                  onChange={(e) => setNewName(e.target.value)}
                  required
                />
              </td>
            </tr>
            <tr>
              <td>
                <input
                  type={showToken ? 'text' : 'password'}
                  maxLength={6}
                  id="security-token"
                  placeholder={t('renameGuild.tokenPlaceholder')}
                  value={token}
                  onChange={(e) => setToken(e.target.value)}
                  required
                />{' '}
                <span
                  className={`far ${showToken ? 'fa-eye-slash' : 'fa-eye'} toggle-token`}
                  role="button"
                  tabIndex={0}
                  onClick={() => setShowToken((s) => !s)}
                />
              </td>
            </tr>
            <tr>
              <td>
                <PaymentMethodSelect value={method} onChange={setMethod} priceEur={price} pdBalance={pdBalance} />
              </td>
            </tr>
            <tr>
              <td>
                <button type="submit" className="rename-guild-button" disabled={busy}>
                  {busy ? t('renameGuild.renaming') : t('renameGuild.renameButton')}
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </form>
      <hr />
      <div className="alert-message" id="rename-guild-response" style={{ display: message ? 'block' : 'none' }}>
        {message && <span className={message.ok ? 'ok-form-response' : 'red-form-response'}>{message.text}</span>}
      </div>
    </div>
  )
}
