import '@/fonts/Inter/inter.css';
import '@/styles/globals.css';
import '@/styles/normalize.css';
// import 'react-loading-skeleton/dist/skeleton.css';

import { useEffect, useState } from 'react';
import dynamic from 'next/dynamic';
import { useRouter, Router } from 'next/router';
import { AnimatePresence, motion } from 'framer-motion';
import { QueryClient, QueryClientProvider } from 'react-query';

import useDevice from '@/core/hooks/useDevice';
import theme from '../../chakra.theme';

const NextProgress = dynamic(() => import('next-progress'), { ssr: false });
const ChakraProvider = dynamic(
  () => import('@chakra-ui/react').then((mod) => mod.ChakraProvider),
  { ssr: false }
);
const ProductProvider = dynamic(
  () => import('@/contexts/ProductContext').then((mod) => mod.ProductProvider),
  { ssr: false }
);
const ProductCartProvider = dynamic(
  () =>
    import('@/contexts/ProductCartContext').then(
      (mod) => mod.ProductCartProvider
    ),
  { ssr: false }
);
const SessionProvider = dynamic(
  () => import('next-auth/react').then((mod) => mod.SessionProvider),
  { ssr: false }
);
const LogoSpinner = dynamic(
  () => import('@/core/components/elements/Spinner/LogoSpinner'),
  { ssr: false }
);
const ScrollToTop = dynamic(() => import('@/core/components/ScrollToTop'), {
  ssr: false,
});
const Toaster = dynamic(
  () => import('react-hot-toast').then((mod) => mod.Toaster),
  { ssr: false }
);

const queryClient = new QueryClient();

function MyApp({ Component, pageProps: { session, ...pageProps } }) {
  const router = useRouter();
  const { isMobile } = useDevice();

  const [animateLoader, setAnimateLoader] = useState(false);

  useEffect(() => {
    const handleRouteChangeStart = () => setAnimateLoader(true);
    const handleRouteChangeComplete = () => setAnimateLoader(false);

    Router.events.on('routeChangeStart', handleRouteChangeStart);
    Router.events.on('routeChangeComplete', handleRouteChangeComplete);
    Router.events.on('routeChangeError', handleRouteChangeComplete);

    return () => {
      Router.events.off('routeChangeStart', handleRouteChangeStart);
      Router.events.off('routeChangeComplete', handleRouteChangeComplete);
      Router.events.off('routeChangeError', handleRouteChangeComplete);
    };
  }, []);

  const [toasterStyle, setToasterStyle] = useState({});

  useEffect(() => {
    let elems = document.querySelectorAll('nav');
    let totalNavHeight = 0;

    elems.forEach(function (elem) {
      totalNavHeight += elem.offsetHeight;
    });

    setToasterStyle({
      marginTop: isMobile ? totalNavHeight - 8 : totalNavHeight,
    });
  }, [isMobile]);

  return (
    <SessionProvider session={session}>
      <ScrollToTop />
      
      <AnimatePresence>
        {animateLoader && (
          <motion.div
            initial={{ opacity: 0.4 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0.4 }}
            transition={{
              duration: 0.1,
            }}
            className='fixed w-screen h-screen z-[500] bg-white flex justify-center items-center'
          >
            <LogoSpinner />
          </motion.div>
        )}
      </AnimatePresence>
      <Toaster
        position='top-center'
        containerStyle={toasterStyle}
        toastOptions={{
          duration: 3000,
          className: 'border border-gray_r-8',
        }}
      />
      <NextProgress color='#F01C21' options={{ showSpinner: false }} />
      <QueryClientProvider client={queryClient}>
        <ProductProvider>
          <ProductCartProvider>
            <ChakraProvider theme={theme}>
              <Component {...pageProps} key={router.asPath} />
            </ChakraProvider>
          </ProductCartProvider>
        </ProductProvider>
      </QueryClientProvider>
    </SessionProvider>
  );
}

export default MyApp;
