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"

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

    const [pageIsLoading, setPageIsLoading] = useState(true)

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

    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>
    }
    </>
  )
}
