import { useEffect, useState } from "react"
import { useDispatch, useSelector } from "react-redux"
import { useNavigate } from "react-router-dom"

import DashboardLayout from "../components/layouts/DashboardLayout"
import PageLoader from "../components/PageLoader"
import { updateUserDetails } from "../store/UserDetails"
import RouteLinks from "../RouteLinks"
import debounceFunction from '../helpers/debounceFunction'


export default function UserExist() {
    const dispatch = useDispatch()
    const navigate = useNavigate()

    const [lastActivityTime, setLastActivityTime] = useState(Date.now()); // HOLDS THE INITIAL TIME USER LOGS IN

    const [pageIsLoading, setPageIsLoading] = useState(true)

    const {userDetails} = useSelector((state) => state.userDetails)


        // Function to log the user out
    const logoutUser = () => {
      localStorage.clear()
      navigate(RouteLinks.login, {replace:true})
      window.location.reload()
    };
  
    // Function to reset the activity time
    const resetTimer = () => {
      debounceFunction(setLastActivityTime(Date.now()), 1000)
    };

    useEffect(()=>{
      const timer = setTimeout(()=>{
        if(Date.now() - Number(lastActivityTime) >= Number(process.env.REACT_APP_TIMEOUT)){
          logoutUser()
        }
      }, Number(process.env.REACT_APP_TIMEOUT))

      // Listen for activity events
      const events = ['mousemove', 'keydown', 'click', 'scroll', 'touchstart'];

      // Adding event listeners
      events.forEach(event => {
        window.addEventListener(event, resetTimer);
      });
      
      return () => {
        clearTimeout(timer)
        events.forEach(event => {
          window.removeEventListener(event, resetTimer);
        })
      }
    },[lastActivityTime])


    useEffect(()=>{
        const loadUser = (token) =>{
            const userExist = [{name:'dummy'}]
            if(userExist && userExist.length > 0){
              dispatch(updateUserDetails(userExist[0]))
              setPageIsLoading(false)
            }else{
                navigate(RouteLinks.login, {replace:true})
            }
        }
        if(userDetails.name){
            setPageIsLoading(false)
        }else if(!userDetails.name && localStorage.getItem('token')){
            loadUser(localStorage.getItem('token'))
        }else{
            navigate(RouteLinks.loginPage, {replace:true})
        }
    },[])

  return (
    <>
    {pageIsLoading ?
    <PageLoader />
    :
    <DashboardLayout></DashboardLayout>
    }
    </>
  )
}
