"use client";

import { useEffect, useState, useRef } from "react";
import { usePathname, useSearchParams } from "next/navigation";
import { useRouter } from "next/navigation";
import PageLoading from "@/components/ui/page-loading";

export function NavigationEvents() {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const router = useRouter();
  const [isLoading, setIsLoading] = useState(false);
  const loadingTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const currentPathRef = useRef(pathname);
  const currentSearchParamsRef = useRef(searchParams);
  const navigationInProgressRef = useRef(false);

  // Mettre à jour les refs quand les valeurs changent
  useEffect(() => {
    currentPathRef.current = pathname;
    currentSearchParamsRef.current = searchParams;
  }, [pathname, searchParams]);

  useEffect(() => {
    // Fonction pour gérer le début de la navigation
    const handleRouteChangeStart = () => {
      // Éviter de déclencher plusieurs chargements simultanés
      if (navigationInProgressRef.current) return;
      
      navigationInProgressRef.current = true;
      setIsLoading(true);
      
      // Ajouter un timeout de sécurité pour éviter un chargement infini
      if (loadingTimeoutRef.current) {
        clearTimeout(loadingTimeoutRef.current);
      }
      
      loadingTimeoutRef.current = setTimeout(() => {
        setIsLoading(false);
        navigationInProgressRef.current = false;
      }, 3000); // 3 secondes maximum de chargement
    };

    // Fonction pour gérer la fin de la navigation
    const handleRouteChangeComplete = () => {
      if (loadingTimeoutRef.current) {
        clearTimeout(loadingTimeoutRef.current);
        loadingTimeoutRef.current = null;
      }
      setIsLoading(false);
      navigationInProgressRef.current = false;
    };

    // Créer un proxy pour intercepter les navigations
    const originalPush = router.push;
    const originalReplace = router.replace;
    const originalBack = router.back;
    const originalForward = router.forward;

    // Remplacer les méthodes de navigation pour détecter les changements
    router.push = (...args) => {
      handleRouteChangeStart();
      return originalPush.apply(router, args);
    };
    
    router.replace = (...args) => {
      handleRouteChangeStart();
      return originalReplace.apply(router, args);
    };
    
    router.back = () => {
      handleRouteChangeStart();
      return originalBack.apply(router);
    };
    
    router.forward = () => {
      handleRouteChangeStart();
      return originalForward.apply(router);
    };

    // Gestionnaire pour le bouton retour/forward du navigateur
    const handlePopState = () => {
      handleRouteChangeStart();
      
      // Vérifier si la navigation est terminée après un court délai
      setTimeout(() => {
        handleRouteChangeComplete();
      }, 500);
    };
    
    window.addEventListener("popstate", handlePopState);
    
    // Nettoyer les écouteurs d'événements et les références
    return () => {
      router.push = originalPush;
      router.replace = originalReplace;
      router.back = originalBack;
      router.forward = originalForward;
      window.removeEventListener("popstate", handlePopState);
      
      if (loadingTimeoutRef.current) {
        clearTimeout(loadingTimeoutRef.current);
      }
      navigationInProgressRef.current = false;
    };
  }, [router]);

  // Réinitialiser l'état de chargement lorsque le chemin ou les paramètres de recherche changent effectivement
  useEffect(() => {
    // Quand un changement de route est détecté, on arrête le chargement
    setIsLoading(false);
    navigationInProgressRef.current = false;
    
    if (loadingTimeoutRef.current) {
      clearTimeout(loadingTimeoutRef.current);
      loadingTimeoutRef.current = null;
    }
  }, [pathname, searchParams]);

  return isLoading ? <PageLoading /> : null;
}
