'use client'

import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { Turnstile } from '@/components/Turnstile'

const ERROR_KEYS = ['invalidEmail', 'invalidUsername', 'captchaFailed'] as const
type RecoverType = 'password' | 'accountname' | 'securitytoken' | 'activation'

export function RecoverForm() {
  const t = useTranslations('Recover')
  const [type, setType] = useState<RecoverType>('password')
  const [value, setValue] = useState('')
  const [captcha, setCaptcha] = useState('')
  const [captchaKey, setCaptchaKey] = useState(0) // remonta el widget para pedir un token nuevo
  const [busy, setBusy] = useState(false)
  const [sent, setSent] = useState(false)
  const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null)

  const usesUsername = type === 'password'

  function changeType(newType: RecoverType) {
    setType(newType)
    setValue('')
    setMessage(null)
    setSent(false)
    setCaptcha('')
    setCaptchaKey((k) => k + 1)
  }

  function resetCaptcha() {
    setCaptcha('')
    setCaptchaKey((k) => k + 1)
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (busy || sent) return
    setBusy(true)
    setMessage(null)
    try {
      const res = await fetch('/api/auth/recover', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ type, value: value.trim(), turnstileToken: captcha }),
      })
      const data: { success?: boolean; error?: string } = await res.json()
      if (data.success) {
        setMessage({ ok: true, text: t('success') })
        setSent(true)
        // Como el original: tras 5 s se restaura el botón y se limpia el formulario.
        setTimeout(() => {
          setSent(false)
          setValue('')
          setMessage(null)
          resetCaptcha()
        }, 5000)
      } else {
        const key = (ERROR_KEYS as readonly string[]).includes(data.error ?? '') ? data.error! : 'genericError'
        setMessage({ ok: false, text: t(key) })
        setTimeout(() => {
          setMessage(null)
          resetCaptcha()
        }, 5000)
      }
    } catch {
      setMessage({ ok: false, text: t('genericError') })
    } finally {
      setBusy(false)
    }
  }

  return (
    <>
      <p>{t('prompt')}</p>
      <br />
      <form noValidate onSubmit={handleSubmit} acceptCharset="utf-8">
        <table className="middle-center-table">
          <tbody>
            <tr>
              <td>
                <select value={type} onChange={(e) => changeType(e.target.value as RecoverType)}>
                  <option value="password">{t('typePassword')}</option>
                  <option value="accountname">{t('typeAccountName')}</option>
                  <option value="securitytoken">{t('typeSecurityToken')}</option>
                  <option value="activation">{t('typeActivation')}</option>
                </select>
              </td>
            </tr>
            <tr>
              <td>
                {usesUsername ? (
                  <input type="text" maxLength={20} placeholder={t('username')} required value={value} onChange={(e) => setValue(e.target.value)} />
                ) : (
                  <input type="email" maxLength={254} placeholder={t('email')} required value={value} onChange={(e) => setValue(e.target.value)} />
                )}
              </td>
            </tr>
            <tr>
              <td>
                <Turnstile key={captchaKey} onVerify={setCaptcha} />
              </td>
            </tr>
            <tr>
              <td>
                <button type="submit" className="recover-button" disabled={busy || sent} style={sent ? { color: '#d79602' } : undefined}>
                  {sent ? t('sent') : busy ? t('sending') : t('submit')}
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </form>
      <hr />
      <div className="alert-message" id="recover-response" style={{ display: message ? 'block' : 'none' }}>
        {message && <span className={message.ok ? 'ok-form-response' : 'red-form-response'}>{message.text}</span>}
      </div>
      <br />
    </>
  )
}
