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

import Logo from '../../assets/images/logo.png'
import { StoreState } from '../../core/models';

export default function DashboardAuth() {

  const navigate = useNavigate()
  const dispatch = useDispatch()
  const {application_uid} = useParams()

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

  const [loading, setLoading] = useState(true)

  useEffect(()=>{
    // let token = localStorage.getItem('token')
    // let uid = localStorage.getItem('uid')
    // if(!token || !uid){ // IF NO TOKEN || UID RETURN TO LOGIN PAGE
    //   navigate(RouteHandler.homepage, {replace:true})
    //   return
    // }
    // const getUser = () => { // FUNCTION TO GET USER BY ID
    //   getUserByID(uid).then(res=>{
    //     if(!res.data.call_return || !Object.keys(res.data.customer).length){
    //       navigate('', {replace:true})
    //       return
    //     }
    //     setLoading(false)
    //     dispatch(updateUserDetails(res.data.customer));
    //   }).catch(err=>{
    //     navigate('', {replace:true})
    //     console.log('USER ERROR', err)
    //   })
    // }

    let token = localStorage.getItem('token')
    if(!token){ // IF NO TOKEN || UID RETURN TO LOGIN PAGE
      navigate(RouteHandler.loginpage, {state:{application_uid}, replace:true})
      return
    }
    if(!application_uid){ // APPLICATION UID RETURN TO LOGIN PAGE
      navigate(RouteHandler.loginpage, {replace:true})
      return
    }
    const getUser = () => { // FUNCTION TO GET USER BY ID
      let data = {firstname:'firstname', lastname:'lastname', uid:'28273737646466464'}
      setLoading(false)
      dispatch(updateUserDetails(data));
    }
    if(!Object.keys(userDetails).length){
      getUser()
    }else{
      setLoading(false)
    }
  },[])

  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>
    :
      <Layout>
        <Outlet />
      </Layout>
    }
    </>
  )
}