'use client'

import { useState } from 'react'
import { useTranslations, useLocale } from 'next-intl'

interface GameAccount {
  id: number
  username: string
  label: string // nombre visible: «15#1» → «WOW1»
}

export function SelectAccountForm({ accounts }: { accounts: GameAccount[] }) {
  const t = useTranslations('SelectAccount')
  const locale = useLocale()
  const [busy, setBusy] = useState<number | null>(null)
  const [error, setError] = useState<string | null>(null)

  async function select(id: number) {
    if (busy !== null) return
    setBusy(id)
    setError(null)
    try {
      const res = await fetch('/api/auth/select-account', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({ accountId: id }),
      })
      const data: { success?: boolean } = await res.json()
      // Navegación completa: re-renderiza el layout/cabecera con la cuenta ya elegida.
      if (data.success) window.location.assign(`/${locale}/my-account/`)
      else {
        setError(t('error'))
        setBusy(null)
      }
    } catch {
      setError(t('error'))
      setBusy(null)
    }
  }

  return (
    <div className="centered">
      <table className="middle-center-table">
        <tbody>
          {accounts.map((a) => (
            <tr key={a.id}>
              <td>
                <button
                  onClick={() => select(a.id)}
                  disabled={busy !== null}
                  className="login-button"
                >
                  {busy === a.id ? t('entering') : a.label}
                </button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
      <div className="alert-message" style={{ display: error ? 'block' : 'none' }}>
        {error && <span className="red-form-response">{error}</span>}
      </div>
    </div>
  )
}
