'use client'

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

const ERROR_KEYS = ['invalidEmail', 'captchaFailed'] as const
const SITE_KEY = process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY

export function RecoverForm() {
  const t = useTranslations('Recover')
  const [type, setType] = useState('password')
  const [email, setEmail] = useState('')
  const [captcha, setCaptcha] = useState('')
  const [busy, setBusy] = useState(false)
  const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null)

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (busy) return
    setBusy(true)
    setMessage(null)
    try {
      const res = await fetch('/api/auth/recover', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ type, email: email.trim(), turnstileToken: captcha }),
      })
      const data: { success?: boolean; error?: string } = await res.json()
      if (data.success) setMessage({ ok: true, text: t('success') })
      else {
        const key = (ERROR_KEYS as readonly string[]).includes(data.error ?? '') ? data.error! : 'genericError'
        setMessage({ ok: false, text: t(key) })
      }
    } catch {
      setMessage({ ok: false, text: t('genericError') })
    } finally {
      setBusy(false)
    }
  }

  const field = 'w-full rounded border border-amber-900/60 bg-[#2c1e14] px-3 py-2'

  return (
    <div className="mx-auto max-w-sm">
      <form onSubmit={handleSubmit} className="space-y-3">
        <label className="block text-left text-sm text-amber-200/70">{t('type')}</label>
        <select value={type} onChange={(e) => setType(e.target.value)} className={field}>
          <option value="password">{t('typePassword')}</option>
          <option value="accountname">{t('typeAccountName')}</option>
          <option value="activation">{t('typeActivation')}</option>
        </select>
        <input type="email" placeholder={t('email')} value={email} onChange={(e) => setEmail(e.target.value)} required className={field} />
        <Turnstile onVerify={setCaptcha} />
        <button type="submit" disabled={busy || (!!SITE_KEY && !captcha)} className="w-full rounded bg-amber-600 px-4 py-2 font-semibold text-[#1b120b] disabled:opacity-60">
          {busy ? t('sending') : t('submit')}
        </button>
      </form>
      {message && <p className={`mt-3 text-center ${message.ok ? 'text-green-400' : 'text-red-400'}`}>{message.text}</p>}
    </div>
  )
}
