import {Divider, List} from "@mui/material";
import {Fragment, useEffect, useReducer, useRef, useState} 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) => {
                    return item.type === "page"
                        ? { ...item, selected: action.route === item.route }
                        : item.subItem && Array.isArray(item.subItem)
                            ? {
                                ...item,
                                subItem: item.subItem.map((subitem) => ({
                                    ...subitem,
                                    selected: subitem.route === action.route,
                                })),
                                showSubItem: item.subItem.some(
                                    (subitem) => subitem.selected
                                ),
                            }
                            : item;
                })
            );
        default:
            throw new Error();
    }
}

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

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


    useEffect(() => {
        selectedKey && document.querySelector(`[data-route="${selectedKey}"]`)?.scrollIntoView({
            behavior: "smooth",
            block: "center"
        });
    }, [selectedKey]);

    return (
        <List sx={{ overflow: "scroll"}}>
            {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>

    );
}
