'use client';

import { useAppSelector } from "@/redux/store"
import { isLoggedIn , mountCheckIfValid } from "@/redux/features/auth-slice";
import { useDispatch } from "react-redux"
import { AppDispatch } from '@/redux/store';
import { useEffect } from "react";
import { useRouter } from 'next/navigation'
import { ReactNode } from 'react' 
import FullScreenLoader from "@/components/common/fullScreenLoader";
import { load } from '@/redux/features/settings-slice'

// HOC for auth pages ( only accept auth user )
export default function LocaleLayout({children} : { children : ReactNode }) {

    const router = useRouter()
    const dispatch = useDispatch<AppDispatch>();
    // load states
    const isValid = useAppSelector((state) => state.authReducer.value.isValid)
    const checkIfValidMounted = useAppSelector((state) => state.authReducer.value.checkIfValidMounted)
    const notAuthRedirectPage = useAppSelector((state) => state.settingsReducer.value.notAuthRedirectPage)
    const isLoadingSettings = useAppSelector((state) => state.settingsReducer.value.isLoadingSettings)
    const loadedFirstTime = useAppSelector((state) => state.settingsReducer.value.loadedFirstTime)
    // Get redux states
    // init isLoggedIn
    useEffect(() => {
        if(checkIfValidMounted) return
        dispatch(mountCheckIfValid())
        async function a()
        {
            await dispatch(isLoggedIn({NotLoggedInCallback}))
        }
        a()
    }, [])
    // load settings
    useEffect(() => {
      if(loadedFirstTime) return
      if(isLoadingSettings) return
      async function a()
      {
        await dispatch(load({page : 1}))
      }
      a()
    }, [])
    // if wasnt logged in this will fire
    function NotLoggedInCallback()
    {
        return router.push(notAuthRedirectPage)
    }
    return (
        <>
            {
                isValid ?
                    <>
                        {children}
                    </>
                :
                <FullScreenLoader />
            }
        </>
    );
}
