import { useEffect, useState, useCallback } from "react";
import { Navigate, Outlet, useLocation, useNavigate } from "react-router-dom";
import usersService from '../services/UsersService'
import LoadingSpinner from '../components/Spinners/LoadingSpinner'
import WrenchBoard from "../assets/images/wrenchboard.png"
import { useDispatch, useSelector } from "react-redux";
import {updateUserDetails} from '../store/UserDetails'


const AuthRoute = ({ redirectPath = "/login", children }) => {
  const apiCall = new usersService()

  const dispatch = useDispatch()

  const [lastActivityTime, setLastActivityTime] = useState(Date.now());
  let [isLogin, setIsLogin] = useState({loading: true, status: false})

  const navigate = useNavigate();

  //Removing Data stored at localStorage after session expires
  const expireSession = () => {
    localStorage.removeItem('session_token');
    localStorage.removeItem('member_id');
    localStorage.removeItem('uid');
    localStorage.removeItem('session');
    navigate("/login", { replace: true }); // redirects user to login page after session expires
  };

  // Reset last activity time on user input
  const resetTime = () => {
    setLastActivityTime(Date.now());
  }
  window.addEventListener('mousemove', resetTime)
  window.addEventListener('keydown', resetTime)

  const loadProfile = ()=>{ // function to load user profile
    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})
    })
  }
  const getProfile = useCallback(()=>{
    loadProfile() // API CALL TO GET USER PROFILE
  }, [])
  
  useEffect(() => {
    getProfile()

    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)
      window.removeEventListener('mousemove', resetTime)
      window.removeEventListener('keydown', resetTime)
    }
  }, [lastActivityTime])

  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;