"use client";

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

export default function ForgotPasswordPage() {
  const [email, setEmail] = useState("");
  const [message, setMessage] = useState<string | null>(null);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  return (
    <main className="mx-auto max-w-xl p-6">
      <h1 className="text-display">Recuperar contrasena</h1>
      <p className="text-body mt-2 text-benell-text-soft">
        Ingresa tu correo y te enviaremos un enlace para restablecer tu contrasena.
      </p>

      <form
        className="mt-6 space-y-4 rounded-benell border border-benell-stroke bg-benell-surface p-5"
        onSubmit={async (event) => {
          event.preventDefault();
          setErrorMessage(null);
          setMessage(null);
          setIsSubmitting(true);

          try {
            const response = await fetch("/api/auth/forgot-password", {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({ email }),
            });

            const payload = (await response.json()) as { message?: string; error?: string };
            if (!response.ok) {
              setErrorMessage(payload.error ?? "No se pudo procesar la solicitud.");
              return;
            }

            setMessage(payload.message ?? "Si el correo existe, enviaremos un enlace para restablecer la contrasena.");
          } catch {
            setErrorMessage("No se pudo procesar la solicitud.");
          } finally {
            setIsSubmitting(false);
          }
        }}
      >
        <label className="block space-y-1.5">
          <span className="text-label font-semibold">Correo electronico</span>
          <input
            type="email"
            value={email}
            onChange={(event) => setEmail(event.target.value)}
            className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2 outline-none focus-visible:ring-2 focus-visible:ring-benell-brown"
            required
          />
        </label>

        {errorMessage ? <p className="text-label text-benell-red">{errorMessage}</p> : null}
        {message ? <p className="text-label text-benell-green">{message}</p> : null}

        <button
          type="submit"
          disabled={isSubmitting}
          className="text-body w-full rounded-pill bg-benell-brown py-3 font-semibold text-white"
        >
          {isSubmitting ? "Enviando..." : "Enviar enlace"}
        </button>
      </form>

      <p className="text-label mt-4 text-benell-text-soft">
        <Link href="/login" className="font-semibold text-benell-brown hover:underline">
          Volver a login
        </Link>
      </p>
    </main>
  );
}
