/**
 * Composant de protection des routes - COOP-CA AMIFOND
 *
 * Protège les routes qui nécessitent une authentification
 */

"use client";

import { ReactNode, useEffect } from "react";

import { useRouter } from "next/navigation";

import { Loader2 } from "lucide-react";

import { useAuth } from "@/hooks/auth/use-auth-queries";

interface ProtectedRouteProps {
  readonly children: ReactNode;
  readonly redirectTo?: string;
  readonly requiredUserTypes?: string[];
}

export function ProtectedRoute({ children, redirectTo = "/auth/login", requiredUserTypes = [] }: ProtectedRouteProps) {
  const router = useRouter();
  const { isAuthenticated, isLoading, user } = useAuth();

  useEffect(() => {
    // Si on n'est pas en cours de chargement et pas authentifié
    if (!isLoading && !isAuthenticated) {
      // Add current path as redirect parameter
      const currentPath = window.location.pathname;
      const redirectUrl = `/auth/login?redirect=${encodeURIComponent(currentPath)}`;
      router.push(redirectUrl);
      return;
    }

    // Si authentifié mais n'a pas le bon type d'utilisateur
    if (isAuthenticated && requiredUserTypes.length > 0 && user) {
      if (!requiredUserTypes.includes(user.user_type)) {
        router.push("/unauthorized");
        return;
      }
    }
  }, [isAuthenticated, isLoading, user, router, redirectTo, requiredUserTypes]);

  // Afficher un loader pendant la vérification
  if (isLoading) {
    return (
      <div className="flex h-screen items-center justify-center">
        <div className="flex flex-col items-center space-y-4">
          <Loader2 className="h-8 w-8 animate-spin" />
          <p className="text-muted-foreground text-sm">Vérification en cours...</p>
        </div>
      </div>
    );
  }

  // Si pas authentifié, ne rien afficher (redirection en cours)
  if (!isAuthenticated) {
    return null;
  }

  // Si authentifié mais n'a pas les bonnes permissions
  if (requiredUserTypes.length > 0 && user && !requiredUserTypes.includes(user.user_type)) {
    return null;
  }

  // Afficher le contenu protégé
  return <>{children}</>;
}
