
import { ReactNode, useEffect, useState } from "react";
import { Outlet, useParams } from "react-router-dom";
import { Header } from "./Header";
import { useAuth } from "../../contexts/AuthContext";
import { Navigate } from "react-router-dom";
import { DashboardSidebar } from "./DashboardSidebar";
import { TravelerBottomNav } from "./TravelerBottomNav";

interface DashboardLayoutProps {
  children: ReactNode;
}

export function DashboardLayout({ children }: DashboardLayoutProps) {
  const { isAuthenticated, currentUser, isLoading } = useAuth();
  const { tripId } = useParams<{ tripId?: string }>();
  const [isNavigationOpen, setIsNavigationOpen] = useState(false);

  // Store last visited trip in localStorage (not sessionStorage) for persistence
  useEffect(() => {
    if (tripId) {
      localStorage.setItem("lastVisitedTrip", tripId);

      // Si nous sommes sur un ID de voyage valide, nous pouvons supprimer le flag pour éviter des redirections futures non désirées
      const isBrowserRefresh = !sessionStorage.getItem('returning_to_tab');
      if (!isBrowserRefresh) {
        sessionStorage.removeItem('justEditedTrip');
      }
    }
  }, [tripId]);

  // Gestion du comportement lors du retour à un onglet
  useEffect(() => {
    if (document.visibilityState !== undefined) {
      const handleVisibilityChange = () => {
        // Don't reload when tab becomes visible again
        if (document.visibilityState === 'visible') {
          // Set flag to prevent auto-refresh
          sessionStorage.setItem('returning_to_tab', 'true');

          // Set timeout to clear the flag
          setTimeout(() => {
            sessionStorage.removeItem('returning_to_tab');
          }, 1000);
        }
      };

      document.addEventListener("visibilitychange", handleVisibilityChange);

      return () => {
        document.removeEventListener("visibilitychange", handleVisibilityChange);
      };
    }
  }, []);

  // Show loading state
  if (isLoading) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-background">
        <div className="flex items-center gap-3 text-base font-semibold text-secondary"><span className="h-3 w-3 animate-pulse rounded-full bg-primary" />Chargement de votre espace…</div>
      </div>
    );
  }

  // Redirect if not authenticated
  if (!isAuthenticated) {
    return <Navigate to="/login" />;
  }

  return (
    <div className="min-h-screen bg-background lg:pl-64">
      <DashboardSidebar open={isNavigationOpen} onClose={() => setIsNavigationOpen(false)} isTraveler={currentUser?.role === "traveler"} />
      <div className="min-h-screen">
        <Header dashboard onMenuClick={() => setIsNavigationOpen(true)} />
        <main className="w-full pb-24 lg:pb-0">{children}</main>
      </div>
      {currentUser?.role === "traveler" && <TravelerBottomNav />}
    </div>
  );
}
