import { useEffect } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { Shield, LogIn } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useAuth } from "@/auth/AuthProvider";

const AUTH_MODE = import.meta.env.VITE_AUTH_MODE ?? "dev";

export function LoginPage() {
  const { login, isAuthenticated, isLoading } = useAuth();
  const navigate = useNavigate();
  const location = useLocation();
  const from = (location.state as { from?: { pathname: string } })?.from?.pathname ?? "/";

  useEffect(() => {
    if (isAuthenticated) {
      navigate(from, { replace: true });
    }
  }, [isAuthenticated, navigate, from]);

  return (
    <div className="min-h-screen flex items-center justify-center bg-background">
      <div className="w-full max-w-sm space-y-8 px-4">
        {/* Logo */}
        <div className="text-center">
          <div className="inline-flex h-16 w-16 rounded-2xl bg-primary items-center justify-center mb-4">
            <Shield className="h-8 w-8 text-primary-foreground" />
          </div>
          <h1 className="text-2xl font-bold">Veylant IA</h1>
          <p className="text-muted-foreground text-sm mt-1">Governance Hub · Dashboard</p>
        </div>

        {/* Login card */}
        <div className="rounded-xl border bg-card p-8 shadow-sm space-y-6">
          <div className="text-center">
            <h2 className="text-lg font-semibold">Connexion</h2>
            {AUTH_MODE === "dev" ? (
              <p className="text-sm text-muted-foreground mt-1">
                Mode développement — authentification simulée
              </p>
            ) : (
              <p className="text-sm text-muted-foreground mt-1">
                Connectez-vous via votre compte Keycloak
              </p>
            )}
          </div>

          <Button
            className="w-full"
            size="lg"
            onClick={login}
            disabled={isLoading}
          >
            <LogIn className="h-4 w-4 mr-2" />
            {AUTH_MODE === "dev" ? "Se connecter (mode dev)" : "Se connecter avec Keycloak"}
          </Button>

          {AUTH_MODE === "dev" && (
            <div className="rounded-lg bg-muted p-3 text-xs text-muted-foreground space-y-1">
              <p className="font-medium">Utilisateurs de test disponibles :</p>
              <p>admin@veylant.dev / admin123</p>
              <p>manager@veylant.dev / manager123</p>
              <p>user@veylant.dev / user123</p>
              <p>auditor@veylant.dev / auditor123</p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
