import { Suspense, useEffect, useMemo } from "react";
import { Outlet, useLocation } from "react-router-dom";
import usePrevious from "react-use/lib/usePrevious";
import Navigation from "@/components/Navigation";
import ChatbotWidget from "@/components/ChatbotWidget";
import Spinner from "@/components/Spinner";
import { useMemoFilterContext } from "@/contexts/MemoFilterContext";
import useMediaQuery from "@/hooks/useMediaQuery";
import { cn } from "@/lib/utils";
import FestiveCorner from "@/components/FestiveCorner";

const RootLayout = () => {
  const location = useLocation();
  const sm = useMediaQuery("sm");
  const { removeFilter } = useMemoFilterContext();
  const pathname = useMemo(() => location.pathname, [location.pathname]);
  const prevPathname = usePrevious(pathname);

  useEffect(() => {
    // When the route changes and there is no filter in the search params, remove all filters
    // Only clear filters if pathname actually changed AND there's no filter param
    // Use location.search to check for filter param to avoid race conditions with searchParams
    if (prevPathname !== pathname && prevPathname !== undefined) {
      const hasFilterInUrl = location.search.includes("filter=");
      if (!hasFilterInUrl) {
        removeFilter(() => true);
      }
    }
  }, [prevPathname, pathname, location.search, removeFilter]);

  return (
    <div className="w-full min-h-full flex flex-row justify-center items-start sm:pl-16">
      {sm && (
        <div
          className={cn(
            "group flex flex-col justify-start items-start fixed top-0 left-0 select-none h-full bg-sidebar",
            "w-16 px-2",
            "border-r border-border",
          )}
        >
          <Navigation className="py-4 md:pt-6" collapsed={true} />
        </div>
      )}
      <main className="w-full h-auto grow shrink flex flex-col justify-start items-center">
        <Suspense
          fallback={
            <div className="w-full h-64 flex items-center justify-center">
              <Spinner size="lg" />
            </div>
          }
        >
          <Outlet />
        </Suspense>
      </main>
      <ChatbotWidget />
      <FestiveCorner />
    </div>
  );
};

export default RootLayout;
