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

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 reducer(state, action) {
    switch (action.type) {
        case "UPDATE_MENU":
            const _permissions = action.permissions || [];
            const filteredPageMenu = filterMenuItems(state, ["all", ..._permissions]);
            return filteredPageMenu;
        case "COLLAPSE_MENU":
            return state.map((item) =>
                action.id == item.id
                    ? {
                          ...item,
                          showSubitems: !item.showSubitems,
                      }
                    : item
            );
        case "COLLAPSE_SUB_ITEMS":
            return state.map((item) => {
                return item.hasSubitems
                    ? {
                          ...item,
                          Subitems: item.Subitems.map((subitem) =>
                              action.id === subitem.id
                                  ? {
                                        ...subitem,
                                        showSubitems: !subitem.showSubitems,
                                    }
                                  : subitem
                          ),
                      }
                    : item;
            });
        case "COLLAPSE_SUB_SECOND_ITEMS":
            return state.map((item) => {
                return item.hasSubitems
                    ? {
                          ...item,
                          Subitems: item.Subitems.map((subitem) => {
                              return subitem.hasSubitems
                                  ? {
                                        ...subitem,
                                        Subitems: subitem.Subitems.map((secondSubitem) =>
                                            action.id === secondSubitem.id
                                                ? {
                                                      ...secondSubitem,
                                                      showSubitems: !secondSubitem.showSubitems,
                                                  }
                                                : secondSubitem
                                        ),
                                    }
                                  : 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 (
        userPermissions && (
            <List disablePadding dense>
                {menuItems.map((menuItem) => {
                    return <SidebarListItems dispatch={dispatch} key={menuItem.id} menuItem={menuItem} />;
                })}
            </List>
        )
    );
};
export default SidebarMenu;
