import { useEffect, useState, useCallback, useMemo } from "react";
import { Navigate, Outlet, useLocation, useNavigate } from "react-router-dom";
import usersService from "../services/UsersService";
import LoadingSpinner from "../components/Spinners/LoadingSpinner";
import { useDispatch, useSelector } from "react-redux";
import { updateUserDetails } from "../store/UserDetails";
import { updateJobs } from "../store/jobLists";
import { updateUserJobList } from "../store/userJobList";

const AuthRoute = ({ redirectPath = "/login", children }) => {
  const apiCall = useMemo(() => new usersService(), []);
  const dispatch = useDispatch();
  const [lastActivityTime, setLastActivityTime] = useState(Date.now());
  const [isLogin, setIsLogin] = useState({ loading: true, status: false });
  const navigate = useNavigate();

  const {jobListTable} = useSelector((state) => state.tableReload)
  
  useEffect(() => {
    //Removing Data stored at localStorage after session expires
    const expireSession = () => {
      localStorage.clear();
      navigate("/login", { replace: true }); // redirects user to login page after session expires
    };

    const checkInactivity = setInterval(() => {
      if (
        Date.now() - lastActivityTime >
        process.env.REACT_APP_SESSION_EXPIRE_MINUTES
      ) {
        expireSession();
      }
    }, process.env.REACT_APP_SESSION_EXPIRE_CHECKER); // Checks for inactivity every minute

    // cleaning up listeners
    return () => {
      clearInterval(checkInactivity);
    };
  }, [lastActivityTime, navigate]);

  // Reset last activity time on user input
  const resetTime = useCallback(() => {
    setLastActivityTime(Date.now());
  }, []);

  useEffect(() => {
    window.addEventListener("mousemove", resetTime);
    window.addEventListener("keydown", resetTime);

    return () => {
      window.removeEventListener("mousemove", resetTime);
      window.removeEventListener("keydown", resetTime);
    };
  }, [resetTime]);

  useEffect(() => {
    if (!isLogin.status) {
      const loadProfile = () => {
        // function to load user profile
        setIsLogin({ loading: true, status: false });
        apiCall
          .loadProfile()
          .then((res) => {
            if (res.data.internal_return < 0) {
              setIsLogin({ loading: false, status: false });
              return;
            }
            dispatch(updateUserDetails(res.data));
            setIsLogin({ loading: false, status: true });
          })
          .catch((error) => {
            setIsLogin({ loading: false, status: false });
          });
      };
      loadProfile();
    }
  }, []);

  useEffect(()=>{
    const getMyJobList = async () => {
      dispatch(updateUserJobList({loading: true, data:[]}))
      try {
        const res = await apiCall.getMyJobList();
        // setMyJobList({loading: false, data:res.data})
        // setMyJobList(res.data);
        dispatch(updateUserJobList({loading: false, data:res.data}))
      } catch (error) {
        dispatch(updateUserJobList({loading: false, data:[]}))
        // setMyJobList({loading: false, data:[]})
        console.log("Error getting mode");
      }
    };
    getMyJobList()
  },[jobListTable])

  useEffect(() => {
    // Getting market data
    const getMarketActiveJobList = async () => {
      try {
        const res = await apiCall.getActiveJobList();
        dispatch(updateJobs(res.data));
      } catch (error) {
        console.log("Error getting mode");
      }
    };
    getMarketActiveJobList();
  }, [apiCall, dispatch]);

  return isLogin.loading ? (
    <LoadingSpinner size="32" color="sky-blue" height="h-screen" />
  ) : // Stills needs fixing
  // <div className="h-screen m-auto">
  //   <img src={WrenchBoard} alt="wrenchboard" className="h-10" />
  // </div>
  !isLogin.status ? (
    <Navigate to={redirectPath} replace />
  ) : (
    children || <Outlet />
  );
};

export default AuthRoute;
