import React, { useEffect, useState } from 'react'
import { useDispatch, useSelector } from "react-redux";
import { Outlet, useNavigate } from 'react-router-dom'
import { useMutation } from '@tanstack/react-query'

import { updateUserDetails } from "../../store/UserDetails";
import { userInfo } from '../../services/services'
import MainLoaderBS from '../loaders/MainLoaderBS'
import Layout from '../layout/Layout'
import siteLinks from '../../links/siteLinks'

import debounceFunction from '../../utils/debounceFunction'
import { SocketContextValues } from '../context/SocketIOContext';


export default function UserExist() {

    const {joinRoom} = SocketContextValues() // Destructures values from socket context

    const navigate = useNavigate()
  
    const [loading, setLoading] = useState(true)

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

    const { userDetails: { token, room }} = useSelector((state) => state?.userDetails); // CHECKS IF USER Details are avaliable, to determine if user is active
  
    let loggedIn = token && room ? true : false; // variable to determine if user is logged in
    // console.log('loggedIn', loggedIn)
  
    // Function to log the user out
    const logoutUser = () => {
      localStorage.clear()
      navigate(siteLinks.login)
      window.location.reload()
    };
  
    // Function to reset the activity time
    const resetTimer = () => {
      debounceFunction(setLastActivityTime(Date.now()), 1000)
    };



    const getUser = useMutation({
      mutationFn: (fields) => {
          return userInfo(fields)
      },
      onError: (error) => {
        navigate(siteLinks.login)
        setLoading(false)
      },
        onSuccess: (res) => {
          const {token, room, uid} = res?.data
          if(!token || !room){
            navigate(siteLinks.login)
            setLoading(false)
            return
          }
          localStorage.setItem('token', token)
          localStorage.setItem('room', room)
          localStorage.setItem('uid', uid)
          dispatch(updateUserDetails({ ...res?.data }));
          setLoading(false)
      }
    })

    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(()=>{
      let token = localStorage.getItem('token') // USER TOKEN
      let uid = localStorage.getItem('uid') // USER UID
      if(token && loggedIn){
        setLoading(false)
      }else if(token && uid && !loggedIn){
        const reqData = {token, uid}
        getUser.mutate(reqData)
      }else{
        navigate(siteLinks.login)
        setLoading(false)
      }
    },[])

    useEffect(()=>{
      if(localStorage.getItem('room')){
        joinRoom(localStorage.getItem('room'));
        joinRoom("merms_global_events"); // global room for all
      }
    },[])

  return (
    <>
    {loading ? 
        <MainLoaderBS />
        :
        <Layout>
          <Outlet />
        </Layout>
    }
    </>
  )
}
