import Stack from "@mui/material/Stack";
import Box from "@mui/material/Box";
import {ThemeSwitch} from "../core/ThemeSwitch";
import Divider from "@mui/material/Divider";
import {renderNavItems} from "./NavItem";
import {navItems} from "../../navItems";
import React, {useEffect, useState} from "react";
import {useLocation} from "react-router-dom";
import {useUser} from "../../hooks/useUser";
import Typography from "@mui/material/Typography";

function renderSpecialItems(items, label, pathname) {
    return (
        <Box>
            <hr/>
            <Typography pl={"20px"} pb={1} variant="subtitle2" color="textSecondary">{label}</Typography>
            {renderNavItems({items: items, pathname: pathname})}
        </Box>
    )
}

export function NavigationMenu() {
    const location = useLocation();
    const pathname = location.pathname;
    const {user} = useUser();
    const [items, setItems] = useState(null)

    const userChild = navItems.filter((item) => !item.forBarmen && !item.forAdmin)
    const barmenChild = navItems.filter((item) => item.forBarmen)
    const adminChild = navItems.filter((item) => item.forAdmin)

    useEffect(() => {
        const role = !user ? "USER" : Object.keys(user).length === 0 ? "USER" : user.role
        const newState = (
            <Box component="nav" sx={{flex: '1 1 auto', p: '12px'}}>
                {renderNavItems({items: userChild, pathname: pathname})}
                {role !== "USER" && renderSpecialItems(barmenChild, "Для бармена:", pathname)}
                {role === "ADMIN" && renderSpecialItems(adminChild, "Для админа", pathname)}
            </Box>
        )
        setItems(newState)
        // eslint-disable-next-line
    }, [user, pathname]);

    return (
        <>
            {/*верхняя стопка*/}
            <Stack spacing={2} sx={{p: 2, height: '63px'}}>
                <ThemeSwitch/>
            </Stack>
            <Divider sx={{borderColor: 'var(--mui-palette-neutral-700)'}}/>
            {/*меню навигации*/}
            {items}
        </>
    )
}