'use client'

import { useState } from 'react'
import { useTranslations, useLocale } from 'next-intl'
import { Turnstile } from '@/components/Turnstile'
import { EMAIL_RE } from '@/lib/bnet'

const ERROR_KEYS = ['invalidCredentials', 'missingFields', 'invalidRequest', 'captchaFailed', 'notAnEmail'] as const

export function LoginForm() {
  const t = useTranslations('Login')
  const locale = useLocale()
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [showPw, setShowPw] = useState(false)
  const [busy, setBusy] = useState(false)
  const [captcha, setCaptcha] = useState('')
  const [captchaKey, setCaptchaKey] = useState(0) // remonta el widget para pedir un token nuevo
  const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null)

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (busy) return
    if (!email.trim() || !password) {
      setMessage({ ok: false, text: t('missingFields') })
      return
    }
    // El <form> lleva noValidate, así que el navegador no comprueba el
    // type="email": si no se mira aquí, se entra con «15#1» y el servidor
    // responde «credenciales incorrectas», que despista.
    if (!EMAIL_RE.test(email.trim())) {
      setMessage({ ok: false, text: t('notAnEmail') })
      return
    }
    setBusy(true)
    setMessage(null)
    try {
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({ email: email.trim(), password, turnstileToken: captcha }),
      })
      const data: { success?: boolean; needsSelection?: boolean; error?: string } = await res.json()
      if (data.success) {
        setMessage({ ok: true, text: t('success') })
        // Navegación completa (no del lado cliente): fuerza que el servidor
        // re-renderice el layout/cabecera con la sesión nueva. Con router.push
        // el layout persiste y la cabecera seguía mostrando "Conectar".
        window.location.assign(`/${locale}${data.needsSelection ? '/select-account' : '/my-account'}`)
        return
      } else {
        const key = (ERROR_KEYS as readonly string[]).includes(data.error ?? '') ? data.error! : 'genericError'
        setMessage({ ok: false, text: t(key) })
        // El token de Turnstile es de un solo uso: tras un fallo hay que resetear
        // el widget para emitir uno nuevo, o el reintento daría "captcha ya usado".
        setCaptcha('')
        setCaptchaKey((k) => k + 1)
        setBusy(false)
      }
    } catch {
      setMessage({ ok: false, text: t('genericError') })
      setCaptcha('')
      setCaptchaKey((k) => k + 1)
      setBusy(false)
    }
  }

  return (
    <>
      <form onSubmit={handleSubmit} acceptCharset="utf-8" noValidate>
        <table className="middle-center-table">
          <tbody>
            <tr>
              <td>
                <input
                  type="email"
                  maxLength={320}
                  name="email"
                  id="username"
                  placeholder={t('email')}
                  autoFocus
                  required
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                />
              </td>
            </tr>
            <tr>
              <td>
                <input
                  type={showPw ? 'text' : 'password'}
                  maxLength={16}
                  name="password"
                  id="password"
                  placeholder={t('password')}
                  required
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                />
                <span
                  className={`far toggle-password ${showPw ? 'fa-eye-slash' : 'fa-eye'}`}
                  onClick={() => setShowPw((v) => !v)}
                  role="button"
                  aria-label="toggle"
                />
              </td>
            </tr>
            <tr>
              <td>
                <Turnstile key={captchaKey} onVerify={setCaptcha} />
              </td>
            </tr>
            <tr>
              <td>
                <button
                  type="submit"
                  className="login-button"
                  disabled={busy}
                >
                  {busy ? t('connecting') : t('submit')}
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </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>
    </>
  )
}
