import { useState } from 'react'
import { useTurnstile } from '../turnstile'

interface Props {
  recoverUrl: string
  csrfToken: string
  siteKey: string
}

const OPTIONS = [
  { value: 'password', label: 'Contraseña' },
  { value: 'accountname', label: 'Nombre de cuenta' },
  { value: 'activation', label: 'Enlace de activación' },
] as const

export function RecoverForm({ recoverUrl, csrfToken, siteKey }: Props) {
  const { ref: turnstileRef, token: captchaToken } = useTurnstile(siteKey)
  const [type, setType] = useState<string>('password')
  const [email, setEmail] = 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)

    const body = new URLSearchParams()
    body.set('type', type)
    body.set('email', email.trim())
    body.set('csrfmiddlewaretoken', csrfToken)
    body.set('cf-turnstile-response', captchaToken)

    try {
      const resp = await fetch(recoverUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'X-CSRFToken': csrfToken,
          Accept: 'application/json',
        },
        credentials: 'same-origin',
        body: body.toString(),
      })
      if (!resp.ok) throw new Error(`HTTP ${resp.status}`)
      const data: { success?: boolean; message?: string } = await resp.json()
      setMessage({ ok: !!data.success, text: data.message || '' })
    } catch {
      setMessage({ ok: false, text: 'Error en el servidor. Inténtalo de nuevo más tarde.' })
    } finally {
      setBusy(false)
    }
  }

  return (
    <>
      <p>Escoge la opción acorde a la información que quieres recuperar</p>
      <br />
      <form id="nw-recover-form" onSubmit={handleSubmit} acceptCharset="utf-8">
        <select id="selection" value={type} onChange={(e) => setType(e.target.value)}>
          {OPTIONS.map((o) => (
            <option key={o.value} value={o.value}>
              {o.label}
            </option>
          ))}
        </select>
        <table className="middle-center-table">
          <tbody>
            <tr>
              <td>
                <input
                  type="email"
                  name="email"
                  id="email"
                  placeholder="Correo electrónico de Gmail"
                  required
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                />
              </td>
            </tr>
            <tr>
              <td>
                <div ref={turnstileRef} className="cf-turnstile" style={{ display: 'inline-block' }} />
              </td>
            </tr>
            <tr>
              <td>
                <button
                  type="submit"
                  className="recover-button"
                  disabled={busy || (!!siteKey && !captchaToken)}
                >
                  {busy ? 'Enviando…' : 'Solicitar'}
                </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>
    </>
  )
}
