import "@/styles/globals.css";
import "react-toastify/dist/ReactToastify.css";
import type { AppProps } from "next/app";

import "primereact/resources/themes/lara-light-indigo/theme.css";
import "primereact/resources/primereact.min.css";
import "primeicons/primeicons.css";
import "react-datepicker/dist/react-datepicker.css";
import { Router, useRouter } from "next/router";
import { useEffect, useState } from "react";
import useExamStore from "@/stores/exam";
import usePreferencesStore from "@/stores/preferencesStore";
import Layout from "../components/High/Layout";
import useEntities from "../hooks/useEntities";
import UserProfileSkeleton from "../components/Medium/UserProfileSkeleton";

export default function App({ Component, pageProps }: AppProps) {
  const [loading, setLoading] = useState(false);

  const { reset } = useExamStore();

  const setIsSidebarMinimized = usePreferencesStore(
    (state) => state.setSidebarMinimized
  );

  const router = useRouter();

  const { entities } = useEntities(!pageProps?.user?.id);

  useEffect(() => {
    const start = () => {
      setLoading(true);
    };
    const end = () => {
     setLoading(false);
    };
    Router.events.on("routeChangeStart", start);
    Router.events.on("routeChangeComplete", end);
    Router.events.on("routeChangeError", end);
    return () => {
      Router.events.off("routeChangeStart", start);
      Router.events.off("routeChangeComplete", end);
      Router.events.off("routeChangeError", end);
    };
  }, []);

  useEffect(() => {
    if (router.pathname !== "/exam" && router.pathname !== "/exercises")
      reset();
  }, [router.pathname, reset]);

  useEffect(() => {
    if (localStorage.getItem("isSidebarMinimized")) {
      if (localStorage.getItem("isSidebarMinimized") === "true") {
        setIsSidebarMinimized(true);
      } else {
        setIsSidebarMinimized(false);
      }
    }
  }, [setIsSidebarMinimized]);

  return (
    <Layout user={pageProps.user} entities={entities} refreshPage={loading}>
      {loading ? (
        <UserProfileSkeleton />
      ) : (
        <Component {...pageProps} entities={entities} />
      )}
    </Layout>
  );
}
