import {Divider, List} from "@mui/material";
import {Fragment, useEffect, useReducer} from "react";
import SidebarListItem from "./SidebarListItem";
import sidebarMenu from "@/core/data/sidebarMenu";
import {useRouter} from "next/router";
import useUser from "@/lib/app/hooks/useUser";

function reducer(state, action) {
    switch (action.type) {
        case "COLLAPSE_MENU":
            return state.map((itemsArr) =>
                itemsArr.map((item) =>
                    action.key == item.key
                        ? {...item, showSubItem: !item.showSubItem}
                        : item
                )
            );
        case "SELECTED":
            return state.map((itemsArr) =>
                itemsArr.map((item) =>
                    action.route == item.route
                        ? {...item, selected: true}
                        : {...item, selected: false}
                )
            );
        default:
            throw new Error();
    }
}

export default function SidebarList({handleDrawerToggle}) {
    const [itemMenu, dispatch] = useReducer(reducer, sidebarMenu);
    const {user} = useUser();

    // activate current page in menu
    const router = useRouter();
    useEffect(() => {
        dispatch({type: "SELECTED", route: router.pathname});
    }, [router.pathname]);

    return (
        <List>
            {itemMenu.map((itemArr, index) => (
                    <Fragment key={index}>
                        {itemArr.map((item) => {
                            if (
                                (item.userType === user.type_id || item.userType === 0) &&
                                (user[item.permission_name] || item.permission_name === "all")
                            ) {
                                return (
                                    <SidebarListItem
                                        item={item}
                                        dispatch={dispatch}
                                        key={item.key}
                                        handleDrawerToggle={handleDrawerToggle}
                                    />
                                );
                            } else {
                                return null;
                            }
                        })}
                        <Divider/>
                    </Fragment>
                )
            )}
        </List>
    )
        ;
}
