'use client'

import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { useRouter } from '@/i18n/navigation'

interface GameAccount {
  id: number
  username: string
}

export function SelectAccountForm({ accounts }: { accounts: GameAccount[] }) {
  const t = useTranslations('SelectAccount')
  const router = useRouter()
  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()
      if (data.success) router.push('/account')
      else {
        setError(t('error'))
        setBusy(null)
      }
    } catch {
      setError(t('error'))
      setBusy(null)
    }
  }

  return (
    <div className="space-y-2">
      {accounts.map((a) => (
        <button
          key={a.id}
          onClick={() => select(a.id)}
          disabled={busy !== null}
          className="w-full nw-btn disabled:opacity-60"
        >
          {busy === a.id ? t('entering') : a.username}
        </button>
      ))}
      {error && <p className="text-red-400">{error}</p>}
    </div>
  )
}
