import qs from "query-string";
import { useLocation, Navigate } from "react-router-dom";
import { useSelector } from "react-redux";
import { useEffect, useRef } from "react";
import { isNullOrEmpty } from "../../../common/Util";
import { LOCAL_STORAGE } from "../../../constants";
const PrivateRoute = ({ element: Component, meta = {}, ...rest }) => {
  //window title
  const defaultTitle = useRef(document.title);
  useEffect(() => {
    document.title = meta.title;
  }, [meta.title]);
  useEffect(
    () => () => {
      document.title = defaultTitle.current;
    },
    []
  );

  const { pathname, search } = useLocation();
  const isLogin = useSelector((state) => state.user.isLogin);
  const isLoginPage = pathname === "/" || pathname === "/login";

  if (!isLogin) {
    const parsedQuery = qs.parse(search);
    const redirectUrl = parsedQuery.redirectUrl;

    const isRedirect = redirectUrl === "/redirect";
    if (isRedirect) {
      const url = "/redirect";
      return <Navigate to={url} replace />;
    }
    if (meta.externalLogin && pathname !== "/redirect") {
      const externalLoginLink = localStorage.getItem(
        LOCAL_STORAGE.EXTERNAL_LOGIN_LINK
      );
      if (!isNullOrEmpty(externalLoginLink) && externalLoginLink !== "undefined") {
        if(externalLoginLink === "Config not Found"){
          // pathname = "/setup"
          // return <Component {...rest} />;
          return <Navigate to={"/setup"} replace />;
        }else{
          window.location.href = externalLoginLink;
        }
      } else {
        return <Navigate to={"/extLoginErr"} replace />;
      }
    }
  }

  if (pathname === "/setup") {
    return <Component {...rest} />;
  }

  if (isLoginPage && isLogin) {
    console.log("Is Login Page", isLoginPage);
    console.log("Is Login", isLogin);
    
    
    const redirectUrl = qs.parse(search).redirectUrl;
    const url = redirectUrl || "/home" + search;
    return <Navigate to={url} replace />;
  }

  if (meta.requiresAuth) {
    if (isLogin) {
      return <Component {...rest} />;
    } else {
      if (!isLoginPage) {
        return <Navigate to={`/login`} replace />;
      }
    }
  }

  return <Component {...rest} />;
};

export default PrivateRoute;
