import React from "react";
import { useLocation } from "react-router-dom/dist";
import { UserContext } from "../../../context/user/userContext";
import { useContext, useEffect, useState } from "react";
import { Navigate } from "react-router-dom/dist";
import loaderContext from "../../../context/loader/LoaderContext";
import { refreshToken } from "../../../services/authService";
export const RequireAuth = ({ children }) => {
  //const search = window.location.search;
  const location = useLocation();
  const [waiting, setWaiting] = useState(true);
  const [processing, setProcessing] = useState(-1);
  const {
    state,
    logout,
    getTokenDetails,
    getBrandSpecificOptions,
    getProfileAndPrivileges,
  } = useContext(UserContext);
  const [renderChildren, shouldRenderChildren] = useState(false);
  const { updateLoaderStatus } = useContext(loaderContext);
  const [isGettingNewToken, setIsGettingNewToken] = useState(false);
  const { hasMultipleBrands, isPrimaryBrand, isSelf, corpBrandCode } = getBrandSpecificOptions();
  useEffect(() => {
    const isAuthenticated = () => {
      const { token, isInValid, isExpired, isExpiring } = getTokenDetails();
      if (isExpired || isInValid) {
        logout();
      } else if (isExpiring) {
        if (isGettingNewToken === false) {
          setIsGettingNewToken(true);
          refreshToken(token).then((res) => {
            setIsGettingNewToken(false);
          });
        }
      } else {
        shouldRenderChildren(true);
        updateLoaderStatus(false);
        const isAuthenticated = state?.user?.isAuthenticated ?? false;
        if (isAuthenticated === false) {
          if (processing === -1) {
            setProcessing(0);
            getProfileAndPrivileges(
              token,
              hasMultipleBrands,
              isPrimaryBrand,
              isSelf,
              corpBrandCode,
              () => {
                setWaiting(false);
                setProcessing(1);
              }
            );
          }
        } else {
          updateLoaderStatus(false);
          setWaiting(false);
        }
      }
    };

    isAuthenticated();
  }, [
    state,
    getTokenDetails,
    getProfileAndPrivileges,
    updateLoaderStatus,
    renderChildren,
    processing,
    logout,
    isGettingNewToken,
    hasMultipleBrands,
    isPrimaryBrand,
    corpBrandCode,
    isSelf
  ]);

  if (waiting) return <React.Fragment></React.Fragment>;
  if (renderChildren) {
    return children;
  }
  return <Navigate to="/login" state={{ from: location }} />;
};
