"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";

const messages: Record<string, string> = {
  invalid_credentials: "Correo o contraseña incorrectos.",
  account_locked: "Demasiados intentos fallidos. La cuenta está bloqueada por 15 minutos.",
  too_many_requests: "Demasiados intentos desde esta conexión. Espera unos minutos.",
};

export default function LoginForm() {
  const router = useRouter();
  const [error, setError] = useState("");
  const [sending, setSending] = useState(false);

  const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setSending(true);
    setError("");
    const data = new FormData(e.currentTarget);
    try {
      const res = await fetch("/api/v1/auth/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: data.get("email"), password: data.get("password") }),
      });
      if (res.ok) {
        router.replace("/admin");
        router.refresh();
        return;
      }
      const body = (await res.json().catch(() => ({}))) as { error?: string };
      setError(messages[body.error ?? ""] ?? "No se pudo iniciar sesión.");
    } catch {
      setError("No se pudo conectar con el servidor.");
    } finally {
      setSending(false);
    }
  };

  const field = "mt-2 w-full border border-ink/15 bg-white px-4 py-3 outline-none transition focus:border-gold";
  return (
    <form onSubmit={onSubmit} className="space-y-5">
      <label className="block text-sm">
        Correo
        <input name="email" type="email" required autoComplete="username" className={field} />
      </label>
      <label className="block text-sm">
        Contraseña
        <input name="password" type="password" required autoComplete="current-password" className={field} />
      </label>
      <button type="submit" disabled={sending} className="w-full bg-ink py-3.5 text-sm tracking-[0.14em] uppercase text-cream transition hover:bg-forest disabled:opacity-60">
        {sending ? "Entrando…" : "Entrar"}
      </button>
      <p className="min-h-5 text-sm text-red-700" role="alert">
        {error}
      </p>
    </form>
  );
}
