
import {useState, useEffect} from 'react'
import DashboardLayout from "./DashboardLayout";
import { Outlet, useNavigate } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";
import { RouteHandler } from '../../router/routes';
import { updateUserDetails } from '../../store/UserDetails';
import { getUserByID } from '../../core/apiRequest';

import Logo from '../../assets/images/logo.png'

export default function DashboardAuth() {

  const navigate = useNavigate()
  const dispatch = useDispatch()

  const { userDetails } = useSelector((state:any) => state?.userDetails); // CHECKS IF USER Details are avaliable

  const [loading, setLoading] = useState(true)

  useEffect(()=>{
    let token = localStorage.getItem('token')
    if(!token){
      navigate(RouteHandler.letsGetStarted, {replace:true})
      return
    }
    const getUser = () => { // FUNCTION TO GET USER BY ID
      // let data = {firstname:'firstname', lastname:'lastname', uid:'28273737646466464'}
      getUserByID().then(res=>{
        if(!res.data.call_return || !Object.keys(res.data.customer).length){
          navigate(RouteHandler.letsGetStarted, {replace:true})
          return
        }
        setLoading(false)
        dispatch(updateUserDetails(res.data.customer));
      }).catch(err=>{
        console.log('USER ERROR', err)
      })
    }
    if(!Object.keys(userDetails).length){
      getUser()
    }
  },[])

  return (
    <>
    {loading && !Object.keys(userDetails).length ?
      <div className='w-full h-screen flex flex-col justify-center items-center gap-4'>
        <img className='animate-pulse' src={Logo} alt='Logo' />
        <p className='animate-pulse'>loading...</p>
      </div>
    :
      <DashboardLayout>
        <Outlet />
      </DashboardLayout>
    }
    </>
  )
}