import Footer from "@/layouts/footer";
import Header from "@/layouts/header";
import "bootstrap/dist/css/bootstrap.min.css";
import "@popperjs/core";
import React, { useEffect, useMemo, useState } from "react";
import store from "@/store/index";
import { Provider } from "react-redux";
import { NotificationContainer } from "react-notifications";
import "react-notifications/lib/notifications.css";
import BreadCrumbs from "@/components/breadcrumbs/breadcrumbs";
import { useRouter } from "next/router";
import CustomDataLoad from "@/other/CustomDataLoad";
import Router from "next/router";
import Loader from "@/components/utils/loader";
import { authApi, customerApi, managerApi } from "@/api/api";
import { loadCart, loadWishlist, loadSetting } from "@/store/index";
import { useLocation } from "react-router-dom";
import FloatIcons from "@/components/floatIcon/floatIcon";
import CategoryMenu from "@/components/utils/categoryMenu";
import { gsap } from "gsap";
import ScrollTrigger from "gsap/dist/ScrollTrigger";
import Lenis from "@studio-freight/lenis";
import "@fortawesome/react-fontawesome";

import "@/styles/globals.css";
import { GoogleReCaptchaProvider } from "react-google-recaptcha-v3";
const App = ({ Component, pageProps }) => {
  const router = useRouter();
  const [isLoading, setIsLoading] = useState(false);
  const [authLoaded, setAuthLoaded] = useState(true);
  const [accountData, setAccountData] = useState({});

  const accountPath = [
    "/account",
    "/account/orders",
    "/account/returned",
    "/account/canceled",
    "/account/address",
    "/account/profile",
    "/order/success",
    "/order/failed",
    "/product/",
  ];
  useEffect(() => {
    Router.events.on("routeChangeStart", async (url) => {
      setIsLoading(true);
      console.log("router:", router.asPath);
      if (accountPath.includes(url)) {
        const accessToken = await onAuthGuard();
        console.log("account accessToken", accessToken);
        if (!accessToken) {
          window.location.href = "/?loginPopup=true";
        }
      }
    });

    Router.events.on("routeChangeComplete", (url) => {
      setIsLoading(false);
    });

    Router.events.on("routeChangeError", (url) => {
      setIsLoading(false);
    });
  }, [Router]);

  // useEffect(() => {
  //   if (typeof window !== undefined) {
  //     // Lenis Smooth Scroll
  //     gsap.registerPlugin(ScrollTrigger);
  //     const lenis = new Lenis();
  //     lenis.on("scroll", ScrollTrigger.update);

  //     gsap.ticker.add((time) => {
  //       lenis.raf(time * 1000);
  //     });

  //     gsap.ticker.lagSmoothing(0);
  //     //
  //   }
  // }, []);

  const onAuthGuard = async () => {
    try {
      let accessToken = "";
      setAuthLoaded(true);
      const response = await authApi.post(
        "/customer/accessToken",
        {},
        { withCredentials: true }
      );
      console.log("response.data.accessToken", response.data.accessToken);
      if (response.data.accessToken) {
        accessToken = response.data.accessToken;
        setAccountData(response.data);
      }
      if (accountPath.includes(router.asPath)) {
        if (!accessToken) {
          window.location.href = "/?loginPopup=true";
        }
      }
      await customerApi.interceptors.request.use(
        (config) => {
          if (accessToken) {
            config.headers["Authorization"] = "Bearer " + accessToken;
          }
          config.withCredentials = true;
          return config;
        },
        (error) => {
          Promise.reject(error);
        }
      );
      await authApi.interceptors.request.use(
        (config) => {
          if (accessToken) {
            config.headers["Authorization"] = "Bearer " + accessToken;
          }
          config.withCredentials = true;
          return config;
        },
        (error) => {
          Promise.reject(error);
        }
      );
      await managerApi.interceptors.request.use(
        (config) => {
          if (accessToken) {
            config.headers["Authorization"] = "Bearer " + accessToken;
          }
          config.withCredentials = true;
          return config;
        },
        (error) => {
          Promise.reject(error);
        }
      );
      loadCart();
      loadWishlist();
      setAuthLoaded(false);
      return accessToken;
    } catch (err) {
      if (accountPath.includes(router.asPath)) {
        window.location.href = "/?loginPopup=true";
      }
      loadCart();
      loadWishlist();
      setAuthLoaded(false);
    }
  };

  useEffect(() => {
    loadSetting();
    if (pageProps.accountData) {
      setAccountData(pageProps.accountData);
    } else {
      onAuthGuard();
    }
    document.documentElement.setAttribute("data-theme", "light");

    customerApi.interceptors.response.use(
      (response) => {
        return response;
      },
      (error) => {
        if (error.response.status === 401) {
          window.location.href = "/?loginPopup=true";
        }
        return error;
      }
    );
  }, []);

  const verifyAuthRequiredURL = () => {
    for (const item of accountPath) {
      if (router.asPath.includes(item)) {
        return true;
      }
    }
    return false;
  };
  return (
    <Provider store={store}>
      <GoogleReCaptchaProvider reCaptchaKey={process.env.NEXT_PUBLIC_SITE_KEY}>
        <FloatIcons />
        {!authLoaded && (
          <>
            <Header
              breadcumbs={router.pathname != "/" && <BreadCrumbs />}
              accountData={accountData}
            />
            {/* <CategoryMenu /> */}
          </>
        )}
        <div className=" screen_height">
          {(isLoading || authLoaded) && (
            <Loader
              className={`${authLoaded ? "fullPageLoader" : "pageLoader"}`}
            />
          )}
          {verifyAuthRequiredURL() && !authLoaded ? (
            <div className={`${authLoaded || isLoading ? "display_none" : ""}`}>
              <Component
                {...pageProps}
                breadcumbs={router.pathname != "/" && <BreadCrumbs />}
              />
            </div>
          ) : (
            !verifyAuthRequiredURL() && (
              <div
                className={`${authLoaded || isLoading ? "display_none" : ""}`}
              >
                <Component
                  {...pageProps}
                  breadcumbs={router.pathname != "/" && <BreadCrumbs />}
                />
              </div>
            )
          )}
        </div>
        <div className={`${authLoaded ? "display_none" : ""}`}>
          <>
            <Footer />
            <CustomDataLoad />
          </>
        </div>
        <NotificationContainer />
      </GoogleReCaptchaProvider>
    </Provider>
  );
};

export default App;
