import LoadingHardPage from "@/core/components/LoadingHardPage";
import RolePermissionMiddleware from "@/middlewares/RolePermission";
import BreadCrumbs from "@/components/layouts/Dashboard/Breadcrumbs";
import FullPageLayout from "@/layouts/FullPageLayout";
import {useEffect, useMemo, useState} from "react";
import sidebarMenu from "@/core/data/sidebarMenu";
import {useRouter} from "next/router";
import {useTranslations} from "next-intl";

const Content = (props) => {
    const t = useTranslations()
    const router = useRouter()
    const [routing, setRouting] = useState(false)
    const [routingItem, setRoutingItem] = useState({})
    const pageList = useMemo(() => {
        const list = []
        for (const menu of sidebarMenu) {
            for (const item of menu) {
                if (item.type === 'menu') {
                    for (const subItem of item.subItem) {
                        list.push(subItem)
                    }
                } else {
                    list.push(item)
                }
            }
        }

        return list
    }, [])

    useEffect(() => {
        const handlerStartRoute = (url) => {
            setRoutingItem(pageList.find(page => page.route === url))
            setRouting(true)
        }
        const handlerCompleteRoute = () => {
            setRouting(false)
        }

        router.events.on('routeChangeStart', handlerStartRoute)
        router.events.on('routeChangeComplete', handlerCompleteRoute)

        return () => {
            router.events.off('routeChangeStart', handlerStartRoute)
            router.events.off('routeChangeComplete', handlerCompleteRoute)
        }
    }, [router]);

    return (
        <FullPageLayout sx={{mt: 3, position: 'relative'}}>
            <LoadingHardPage icon={routingItem?.icon}
                             label={routingItem?.key ? `${t('routing_to')} ${t(routingItem?.key)}` : ''}
                             loading={routing} width={100} height={100}
                             sx={{position: "absolute", bgcolor: "#fffc"}}>
                <RolePermissionMiddleware requiredPermissions={props.permissions}>
                    <BreadCrumbs isVisible={true}/>
                    {props.children}
                </RolePermissionMiddleware>
            </LoadingHardPage>
        </FullPageLayout>
    )
}

export default Content