"use client";
import { usePermissions } from "@/lib/hooks/usePermissions";
import { List } from "@mui/material";
import { usePathname } from "next/navigation";
import { useEffect, useReducer, useState } from "react";
import Profile from "@/core/components/Profile";
import { filterMenuItems } from "@/core/utils/filterMenuItems";
import { pageMenu } from "@/core/utils/pageMenu";
import SidebarListItems from "./SidebarListItems";

function selectPage(item, route) {
    if (item.type === "page") {
        return {
            ...item,
            selected: item.route === route,
            showSubitems: item.route === route,
        };
    } else if (item.Subitems && Array.isArray(item.Subitems)) {
        const updatedSubitems = item.Subitems.map((subitem) => selectPage(subitem, route));
        return {
            ...item,
            Subitems: updatedSubitems,
            showSubitems: updatedSubitems.some((subitem) => subitem.showSubitems || subitem.route === route),
        };
    }
    return item;
}

function toggleSubitems(items, actionId) {
    return items.map((item) =>
        actionId === item.id ? { ...item, showSubitems: !item.showSubitems } : { ...item, showSubitems: false }
    );
}

function reducer(state, action) {
    switch (action.type) {
        case "UPDATE_MENU":
            const _permissions = action.permissions || [];
            return filterMenuItems(state, ["all", ..._permissions]);

        case "COLLAPSE_MENU":
            return state.map((item) => ({
                ...item,
                showSubitems: item.id === action.id ? !item.showSubitems : false,
            }));

        case "COLLAPSE_SUB_ITEMS":
            return state.map((item) =>
                item.hasSubitems ? { ...item, Subitems: toggleSubitems(item.Subitems, action.id) } : item
            );

        case "COLLAPSE_SUB_SECOND_ITEMS":
            return state.map((item) =>
                item.hasSubitems
                    ? {
                          ...item,
                          Subitems: item.Subitems.map((subitem) =>
                              subitem.hasSubitems
                                  ? {
                                        ...subitem,
                                        Subitems: toggleSubitems(subitem.Subitems, action.id),
                                    }
                                  : subitem
                          ),
                      }
                    : item
            );

        case "SELECTED":
            return state.map((item) => selectPage(item, action.route));

        default:
            throw new Error();
    }
}

const SidebarMenu = () => {
    const { data: userPermissions } = usePermissions();
    const [menuItems, dispatch] = useReducer(reducer, pageMenu);
    const pathname = usePathname();
    const [selectedKey, setSelectedKey] = useState(null);

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

    useEffect(() => {
        if (!userPermissions) return;
        dispatch({ type: "UPDATE_MENU", permissions: userPermissions });
    }, [userPermissions]);

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

    return (
        <>
            <Profile />
            {userPermissions && (
                <List sx={{ overflow: "auto", flex: 1 }} disablePadding dense>
                    {menuItems.map((menuItem) => {
                        return <SidebarListItems dispatch={dispatch} key={menuItem.id} menuItem={menuItem} />;
                    })}
                </List>
            )}
        </>
    );
};
export default SidebarMenu;
