import React, { useEffect, useContext } from "react";
import { UserContext } from "../../../context/user/userContext";
import {
  isGivenTokenExpired,
  isGivenTokenExpiring,
  setStorageToken,
} from "../../../services/tokenService";
import {
  setCorpBrandCode,
  setHasMultipleBrands,
  setIsPrimaryBrand,
  setIsSelf
} from "../../../services/localstorageService";
export const Login = ({brandCode}) => {
  const { login, logout, removeAll, replaceUrl } = useContext(UserContext);

  const search = window.location.search;
  const queryToken = new URLSearchParams(search).get("token");
  const hasMultipleBrandsValue = new URLSearchParams(search).get("hmb");
  const isPrimaryBrandValue = new URLSearchParams(search).get("ipb");
  const isSelfValue = new URLSearchParams(search).get("islf");
  const corpBrandCodeValue = new URLSearchParams(search).get("cbc");
  const queryDashboard =
    new URLSearchParams(search).get("dashboard") ?? "";
  useEffect(() => {
    const checkIfTokenValid = () => {
      let shouldReplaceUrl = false;
      try {
        const isValidQueryToken = () => {
          return (
            queryToken !== null &&
            queryToken !== "" &&
            queryToken !== undefined &&
            queryToken !== "null"
          );
        };

        if (isValidQueryToken()) {
          if (
            isGivenTokenExpiring(queryToken) ||
            isGivenTokenExpired(queryToken)
          ) {
            logout();
          } else {
            removeAll();
            setStorageToken(queryToken);
            setHasMultipleBrands(hasMultipleBrandsValue);
            setIsPrimaryBrand(isPrimaryBrandValue);
            setIsSelf(isSelfValue);
            setCorpBrandCode(corpBrandCodeValue);
            shouldReplaceUrl = true;
          }
        } else {
          logout();
        }

        if (shouldReplaceUrl) {
          console.log("querydashboard", queryDashboard);        
          window.location.replace("/franchisee-mgmt/manage/roles");
         // replaceUrl(queryDashboard);
        }
      } catch (err) {
        console.log(err);
        logout();
      }
    };
    checkIfTokenValid();
  }, [
    queryToken,
    login,
    logout,
    replaceUrl,
    queryDashboard,
    hasMultipleBrandsValue,
    isPrimaryBrandValue,
    isSelfValue,
    removeAll,
    corpBrandCodeValue
  ]);

  return <div className="overlay-loading"></div>;
};


