'use client'

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

function transferErrorKey(error?: string): string {
  switch (error) {
    case 'missingFields':
    case 'invalidAmount':
    case 'invalidToken':
    case 'characterNotFound':
    case 'sameAccount':
    case 'insufficientFunds':
    case 'notAuthenticated':
      return error
    default:
      return 'generic'
  }
}

export function TransferDPointsForm({ balance }: { balance: number }) {
  const t = useTranslations('Points')
  const transferError = (error?: string) => t(`transferDp.errors.${transferErrorKey(error)}`)
  const router = useRouter()
  const [character, setCharacter] = useState('')
  const [amount, setAmount] = useState('')
  const [token, setToken] = useState('')
  const [busy, setBusy] = useState(false)
  const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null)

  if (balance <= 0) {
    return (
      <div className="centered">
        <br />
        <br />
        <span>{t('transferDp.noPd')}</span>
        <br />
      </div>
    )
  }

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    if (busy) return
    const n = Number(amount)
    if (!character.trim() || !token.trim()) {
      setMessage({ ok: false, text: transferError('missingFields') })
      return
    }
    if (!Number.isInteger(n) || n <= 0) {
      setMessage({ ok: false, text: transferError('invalidAmount') })
      return
    }
    if (n > balance) {
      setMessage({ ok: false, text: transferError('insufficientFunds') })
      return
    }
    if (!window.confirm(t('transferDp.confirm', { n, character: character.trim() }))) return

    setBusy(true)
    setMessage(null)
    try {
      const res = await fetch('/api/dpoints/transfer', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({ character: character.trim(), amount: n, token: token.trim() }),
      })
      const data: { success?: boolean; error?: string } = await res.json()
      if (data.success) {
        setMessage({ ok: true, text: t('transferDp.success', { n, character: character.trim() }) })
        setCharacter('')
        setAmount('')
        setToken('')
        router.refresh()
      } else {
        setMessage({ ok: false, text: transferError(data.error) })
      }
    } catch {
      setMessage({ ok: false, text: transferError() })
    } finally {
      setBusy(false)
    }
  }

  return (
    <div className="centered">
      <br />
      <p className="yellow-info centered">{t('transferDp.available', { balance })}</p>
      <br />
      <form noValidate onSubmit={handleSubmit} acceptCharset="utf-8">
        <input
          type="text"
          placeholder={t('transferDp.characterPlaceholder')}
          value={character}
          onChange={(e) => setCharacter(e.target.value)}
          required
        />
        <br />
        <input
          type="number"
          placeholder={t('transferDp.amountPlaceholder')}
          min="1"
          max={balance}
          step="1"
          value={amount}
          onChange={(e) => setAmount(e.target.value)}
          required
        />
        <br />
        <input
          type="text"
          placeholder={t('transferDp.tokenPlaceholder')}
          maxLength={6}
          value={token}
          onChange={(e) => setToken(e.target.value)}
          required
        />
        <br />
        <button type="submit" className="transfer-button" disabled={busy}>
          {busy ? t('transferDp.transferring') : t('transferDp.transferButton')}
        </button>
      </form>
      <hr />
      <div className="alert-message" style={{ display: message ? 'block' : 'none' }}>
        {message && <span className={message.ok ? 'ok-form-response' : 'red-form-response'}>{message.text}</span>}
      </div>
    </div>
  )
}
