import { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'

// project import
import LoginRoutes from './LoginRoutes'
// import MainRoutes from './MainRoutes'
import PublicUserRoutes from './PublicUserRoutes'
import GLDUserRoutes from './GLDUserRoutes'
import TestRoutes from './_TestRoutes'
import { useRoutes } from 'react-router-dom'
import {
    isUserLoggedIn,
    // isAdminLoggedIn,
    isGLDLoggedIn,
    isINDLoggedIn,
    isORGLoggedIn,
} from "utils/Utils";
import { Navigate } from "react-router";
import {
    SetupAxiosInterceptors,
} from "auth/index";
import SettingRoutes from './SettingRoutes';
import AfterLoginRoutes from './AfterLoginRoutes';

// ==============================|| ROUTING RENDER ||============================== //

export default function ThemeRoutes() {
    const dispatch = useDispatch()
    /** Re-run route config when auth changes (same-tab LOGIN/LOGOUT or another tab touching userData). */
    useSelector((state) => state.authRevision)

    useEffect(() => {
        const onStorage = (e) => {
            if (e.key === 'userData') {
                dispatch({ type: 'AUTH_STORAGE_SYNC' })
            }
        }
        window.addEventListener('storage', onStorage)
        return () => window.removeEventListener('storage', onStorage)
    }, [dispatch])

    // Must run every render: SetupAxiosInterceptors uses useNavigate/useDispatch. Wrapping it in
    // isUserLoggedIn() caused fewer hooks after logout (e.g. Change Password → Back to Login).
    // Interceptor registration is still guarded inside by axiosInterceptorsSetup.
    SetupAxiosInterceptors();
    // console.log();
    return useRoutes([{
        path: '',
        children: [
            (
                isUserLoggedIn() ?
                    {
                        path: '',
                        element: <Navigate to="/dashboard" />
                    }
                :
                    {
                        path: '',
                        element: <Navigate to="/login" />
                    }
            )
        ]
    },
    // isUserLoggedIn() ? MainRoutes : LoginRoutes,
    isUserLoggedIn() ? AfterLoginRoutes :
    {
            path: '/dashboard',
            element: <Navigate to="/login" />
    },
    isUserLoggedIn() && isINDLoggedIn() || isUserLoggedIn() && isORGLoggedIn() ? PublicUserRoutes : LoginRoutes,
    isUserLoggedIn() && isGLDLoggedIn() ? SettingRoutes : LoginRoutes,
    isUserLoggedIn() && isGLDLoggedIn() ? GLDUserRoutes : LoginRoutes,
    !isUserLoggedIn() ? {
        path: '*',
        element: <Navigate to="/login" />
    } :
        {
            path: '*',
            element: <Navigate to="/dashboard" />
        },
    isUserLoggedIn() && isGLDLoggedIn() && JSON.parse(localStorage.getItem('userData')).fullenName == "2fi" ? TestRoutes : {},

    ]);
}
