import { useState } from 'react'

export interface GameAccount {
  id: number
  username: string
  index: number
}

interface Props {
  accounts: GameAccount[]
  selectUrl: string
}

export function SelectAccount({ accounts, selectUrl }: Props) {
  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 r = await fetch(`${selectUrl}?account_id=${id}`, {
        headers: { Accept: 'application/json' },
        credentials: 'same-origin',
      })
      const d: { success?: boolean; redirect?: string; error?: string } = await r.json()
      if (d.success && d.redirect) {
        window.location.href = d.redirect
      } else {
        setError(d.error || 'No se pudo seleccionar la cuenta.')
        setBusy(null)
      }
    } catch {
      setError('Error de red. Inténtalo de nuevo.')
      setBusy(null)
    }
  }

  return (
    <table className="middle-center-table">
      <tbody>
        {accounts.map((a) => (
          <tr key={a.id}>
            <td>
              <button
                type="button"
                className="login-button"
                disabled={busy !== null}
                onClick={() => select(a.id)}
              >
                {busy === a.id ? 'Entrando…' : a.username}
              </button>
            </td>
          </tr>
        ))}
        {error && (
          <tr>
            <td>
              <span className="red-form-response">{error}</span>
            </td>
          </tr>
        )}
      </tbody>
    </table>
  )
}
