'use client';

import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useDispatch, useSelector } from 'react-redux';
import {
	fetchAuthData,
	isAuthenticatedSelector,
	isLoadingSelector,
} from '@/store/authSlice';
import { AppDispatch } from '@/store/app';
import Preloader from '@/components/landing/Preloader';

export default function AuthLayout({
	children,
}: {
	children: React.ReactNode;
}) {
	const router = useRouter();
	const dispatch = useDispatch<AppDispatch>();
	const isAuthenticated = useSelector(isAuthenticatedSelector);
	const isLoading = useSelector(isLoadingSelector);

	useEffect(() => {
		if (!isLoading && isAuthenticated) {
			router.replace('/admin/dashboard');
		} else if (isLoading) {
			dispatch(fetchAuthData());
		}
	}, [isAuthenticated, isLoading, router, dispatch]);

	if (isLoading || isAuthenticated) {
		return <Preloader />
	}

	return <div>{children}</div>;
}
