"use client";

import { useState, useEffect } from "react";
import { Lock, Mail, Loader2, AlertCircle } from "lucide-react";

export default function LoginPage() {
  const [email, setEmail] = useState("admin@demo.local");
  const [password, setPassword] = useState("1234");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  // Seguridad: Asegurar que el estado de carga se limpie al montar el componente
  useEffect(() => {
    setLoading(false);
  }, []);

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setLoading(true);
    setError("");

    try {
      // Detectamos el host actual (localhost o la IP de la red)
      const host = window.location.origin;
      
      const res = await fetch(`${host}/api/auth/login`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        credentials: "include",
        body: JSON.stringify({ email, password }),
      });

      const data = await res.json().catch(() => ({ error: "Respuesta inválida del servidor" }));

      if (!res.ok) {
        setError(data.error || "Credenciales incorrectas");
        setLoading(false);
        return;
      }

      if (!data?.user?.role) {
        setError("Error: El servidor no devolvió un rol de usuario.");
        setLoading(false);
        return;
      }

      // REDIRECCIONAMIENTO DINÁMICO
      const role = data.user.role;
      if (role === "admin") {
        window.location.replace("/admin/dashboard");
      } else if (role === "leader") {
        window.location.replace("/leader/dashboard");
      } else if (role === "brigadist") {
        window.location.replace("/brigadist/dashboard");
      } else {
        setError("Rol no reconocido: " + role);
      }

    } catch (err: any) {
      console.error("LOGIN ERROR:", err);
      setError("Error de conexión: " + (err.message === "Failed to fetch" ? "Servidor no alcanzable" : err.message));
    } finally {
      // Importante: No ponemos false aquí si hubo redirección exitosa para evitar parpadeos
      // Pero si hay error, el flujo llegará aquí
      if (error) setLoading(false);
    }
  }

  return (
    <div className="min-h-screen flex items-center justify-center p-6 bg-[#050505]">
      <div className="w-full max-w-md">
        <form
          onSubmit={handleSubmit}
          className="rounded-[2.5rem] border border-gray-900 p-10 shadow-2xl bg-[#0a0a0a] text-white relative overflow-hidden"
        >
          {/* Decoración estética JAMPA */}
          <div className="absolute top-0 right-0 w-32 h-32 bg-blue-600/5 blur-[50px] rounded-full -mr-16 -mt-16"></div>

          <header className="mb-10">
            <h1 className="text-4xl font-black uppercase tracking-tighter italic mb-2">JAMPA</h1>
            <p className="text-gray-500 text-[10px] font-black uppercase tracking-[0.2em]">Political System v1.0</p>
          </header>

          <div className="space-y-6">
            {/* Campo Email */}
            <div>
              <label className="mb-2 flex items-center gap-2 text-[10px] font-black uppercase text-gray-500 tracking-widest">
                <Mail size={12} className="text-blue-500" /> Correo Electrónico
              </label>
              <input
                type="email"
                autoComplete="username"
                className="w-full rounded-2xl border border-gray-800 bg-[#0d0d0d] px-5 py-4 text-sm text-white focus:border-blue-500 focus:ring-1 focus:ring-blue-500 outline-none transition-all placeholder:text-gray-700 font-medium"
                placeholder="usuario@jampa.mx"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                required
              />
            </div>

            {/* Campo Password */}
            <div>
              <label className="mb-2 flex items-center gap-2 text-[10px] font-black uppercase text-gray-500 tracking-widest">
                <Lock size={12} className="text-blue-500" /> Contraseña
              </label>
              <input
                type="password"
                autoComplete="current-password"
                className="w-full rounded-2xl border border-gray-800 bg-[#0d0d0d] px-5 py-4 text-sm text-white focus:border-blue-500 focus:ring-1 focus:ring-blue-500 outline-none transition-all placeholder:text-gray-700"
                placeholder="••••••••"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                required
              />
            </div>
          </div>

          {/* Mensaje de Error */}
          {error && (
            <div className="mt-8 flex items-center gap-3 rounded-2xl bg-red-500/10 border border-red-500/20 p-4 text-[11px] font-bold text-red-400 animate-in fade-in slide-in-from-top-2 duration-300">
              <AlertCircle size={16} className="shrink-0" />
              {error}
            </div>
          )}

          {/* Botón de Entrada */}
          <button
            type="submit"
            disabled={loading}
            className={`mt-10 w-full rounded-2xl py-5 text-xs font-black uppercase tracking-[0.2em] shadow-xl transition-all flex items-center justify-center gap-3 
              ${loading 
                ? "bg-gray-800 text-gray-600 cursor-not-allowed" 
                : "bg-white text-black hover:bg-blue-500 hover:text-white cursor-pointer active:scale-95"
              }`}
          >
            {loading ? (
              <>
                <Loader2 size={16} className="animate-spin" />
                Autenticando...
              </>
            ) : (
              "Entrar al Sistema"
            )}
          </button>
        </form>

        <p className="mt-8 text-center text-[10px] font-black text-gray-700 uppercase tracking-widest">
          Propiedad de JAMPA Solutions &copy; 2026
        </p>
      </div>
    </div>
  );
}