import { Outlet, useRouterState } from "@tanstack/react-router";
import Drawer from "../components/Drawer/Drawer";
import { useDrawerStore } from "../context/zustand-store/appStore";
import { checkIsMobile } from "../utils/checkIsMobile";
import BottomNavigation from "../screen/BottomNavigation";
import Navbar from "../screen/NavBar";
import Backdrop from "../components/BackDrop/Backdrop";
import Modal from "../components/Modal/Modal";
import { useUserStore } from "../context/zustand-store/userStore";
import "../App.css";
import { SideBar } from "../screen/SideBar";
import { motion, AnimatePresence } from "framer-motion";
import { useEffect, useRef } from "react";

const sidebarVariants = {
  hidden: { opacity: 0, x: 50 },
  visible: {
    opacity: 1,
    x: 0,
    transition: {
      type: "spring" as const,
      stiffness: 300,
      damping: 30,
    },
  },
  exit: {
    opacity: 0,
    x: 50,
    transition: {
      type: "tween" as const,
      ease: "easeInOut" as const,
      duration: 0.25,
    },
  },
};

export const RootLayout = () => {
  const { drawerState } = useDrawerStore();
  const contentRef = useRef<HTMLDivElement>(null);
  const { auth } = useUserStore();
  const isMobile = checkIsMobile();
  const location = useRouterState({ select: (state) => state.location });

  useEffect(() => {
    contentRef.current?.scrollTo(0, 0);
  }, [location.pathname]);

  return (
    <div className="h-screen flex flex-col relative bg-white dark:bg-dark-900 overflow-hidden">
      {auth && <Navbar />}
      {drawerState?.isOpen && <Drawer />}

      <motion.div
        layout
        layoutId="root-container"
        className={`flex flex-1 ${auth ? "overflow-hidden" : "h-full"}`}
      >
        {auth && (
          <AnimatePresence mode="popLayout">
            <motion.div
              layout
              key="sidebar"
              variants={sidebarVariants}
              initial="hidden"
              animate="visible"
              exit="exit"
              className={`hidden sm:block`}
              style={{ zIndex: 10 }}
            >
              <SideBar />
            </motion.div>
          </AnimatePresence>
        )}

        <motion.div
          ref={contentRef}
          layout
          layoutId="content"
          className={`flex-1 ${
            auth ? "overflow-y-auto pt-2 px-2" : "h-screen overflow-hidden"
          } ${auth && isMobile ? "select-none" : "pb-4"} ${
            drawerState.isOpen && "blur-[1px] "
          }`}
          key="content"
        >
          <Outlet />
        </motion.div>
      </motion.div>

      <Backdrop />
      <Modal />
      {isMobile && auth && <BottomNavigation />}
    </div>
  );
};
