import { Outlet, useNavigate } from "react-router";
import { useEffect, useState } from "react";
import { useGetCurrentUser } from "../../../hooks/useGetCurrentUser";
import { CgSpinner } from "react-icons/cg";
import styles from "./styles.module.css";

export default function AdminLayout() {
    const navigate = useNavigate();
    const [loading, setLoading] = useState(true);

    /* Verificação do role_id no frontend das páginas do admin */
    const { getCurrentUser } = useGetCurrentUser();

    useEffect(() => {
        const fetchCurrentUser = async () => {
            setLoading(true);
            try {
                const currentUser = await getCurrentUser();

                if (currentUser.data.role_id !== 1) {
                    navigate("/dashboard", { replace: true });
                    return;
                }

                setLoading(false);
            } catch (error) {
                navigate("/dashboard", { replace: true });
            } 
        };
        fetchCurrentUser();
    }, []);

    if (loading) {
        return <div className="text-center mt-5 d-flex flex-column gap-2 align-items-center">
            <CgSpinner className={`${styles.animateSpin} text-2xl fs-3`} />
        </div>;
    }

    return <Outlet />;


    /* Criado o layout para o admin, o proximo passo é aninhar este layout em routes.tsx no frontend */
}