import {Divider, List} from "@mui/material";
import {Fragment, useEffect, useReducer, 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, routing: false
                } : item.subItem && Array.isArray(item.subItem) ? {
                    ...item, subItem: item.subItem.map((subitem) => ({
                        ...subitem, selected: subitem.route === action.route, routing: false
                    })), showSubItem: item.subItem.some((subitem) => subitem.selected),
                } : item;
            }));
        case "SELECTING":
            return state.map((itemsArr) => itemsArr.map((item) => {
                return item.type === "page" ? {
                    ...item, selected: action.route === item.route, routing: action.route === item.route
                } : item.subItem && Array.isArray(item.subItem) ? {
                    ...item, subItem: item.subItem.map((subitem) => ({
                        ...subitem, selected: subitem.route === action.route, routing: 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);
        const handlerStartRoute = (url) => {
            dispatch({type: "SELECTING", route: url});
        }

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

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


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

    return (<List dense={true} sx={{overflow: "scroll", p: 0}}>
        {itemMenu.map((itemArr, index) => {
            let isDividerVisible = false;
            return (<Fragment key={index}>
                {itemArr.map((item) => <Fragment key={item.key}>
                    {(item.permissions.some((permission) => user?.permissions?.includes(permission)) || item.permissions.includes('all')) && <>
                        <SidebarListItem
                            item={item}
                            dispatch={dispatch}
                            handleDrawerToggle={handleDrawerToggle}
                        />
                        {isDividerVisible = true}
                    </>}
                </Fragment>)}
                {isDividerVisible && <Divider/>}
            </Fragment>)
        })}
    </List>);
}
