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) => {
                        console.log(item)
                        if (item.type === "page") {
                            if (action.route === item.route)
                                return {...item, selected: true}
                            else
                                return {...item, selected: false}
                        }
                        return {...item}
                        // item.subItem.map((subitem) => {
                        //     if (action.route === subitem.route)
                        //         return {...item, showSubItem: true, subItem: {...subitem, selected: true}}
                        //     else
                        //         return {...item, showSubItem: false, subItem: {...subitem, selected: false}}
                        // })
                    }
                )
            );
        default:
            throw new Error();
    }
}

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

    useEffect(() => {
        dispatch({type: "SELECTED", route: router.pathname});
    }, [router.pathname]);

    return (
        <List>
            {itemMenu.map((itemArr, index) => (
                <Fragment key={index}>
                    {itemArr.map((item) =>
                        <Fragment key={item.key}>
                            {(user.permissions.includes(item.permission) || item.permission === "all") &&
                                <SidebarListItem
                                    item={item}
                                    dispatch={dispatch}
                                    handleDrawerToggle={handleDrawerToggle}
                                />}
                        </Fragment>
                    )}
                    <Divider/>
                </Fragment>
            ))}
        </List>

    );
}
