'use client';

import { useState } from 'react';
import Link from 'next/link';

export default function RecoverPage() {
  const [email, setEmail] = useState('');
  const [sent, setSent] = useState(false);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  const submit = async (event: React.FormEvent) => {
    event.preventDefault();
    setError('');
    setLoading(true);
    try {
      const response = await fetch('/api/auth/password-reset/request', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      });
      if (!response.ok) {
        const data = await response.json().catch(() => null);
        setError(data?.error?.message ?? 'No se pudo solicitar el enlace.');
        return;
      }
      setSent(true);
    } catch {
      setError('No se pudo conectar con el servidor.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <main className="max-w-md mx-auto px-4 py-16">
      <div className="rounded-2xl border border-gray-200 bg-white p-8 shadow-sm">
        <h1 className="mb-2 text-2xl font-bold text-gray-900">Recuperar contraseña</h1>
        {sent ? (
          <p className="rounded-lg bg-green-50 px-4 py-3 text-sm text-green-700">Si existe una cuenta con ese email, recibirás un enlace de recuperación.</p>
        ) : (
          <form onSubmit={submit} className="space-y-4">
            <p className="text-sm text-gray-500">Te enviaremos un enlace para elegir una contraseña nueva.</p>
            <label className="block text-sm font-medium text-gray-700">Email
              <input type="email" required value={email} onChange={(e) => setEmail(e.target.value)} className="mt-1 w-full rounded-xl border border-gray-300 px-4 py-3 outline-none focus:ring-2 focus:ring-[#70ad47]" />
            </label>
            {error && <p className="rounded-lg bg-red-50 px-4 py-3 text-sm text-red-700">{error}</p>}
            <button disabled={loading} className="w-full rounded-xl bg-[#70ad47] py-3 font-semibold text-white hover:bg-[#5a9040] disabled:opacity-60">{loading ? 'Enviando...' : 'Enviar enlace'}</button>
          </form>
        )}
        <Link href="/auth/login" className="mt-5 block text-center text-sm text-[#70ad47] hover:underline">Volver a iniciar sesión</Link>
      </div>
    </main>
  );
}
