import { Divider, List } from "@mui/material";
import { 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) =>
          action.route == item.route
            ? { ...item, selected: true }
            : { ...item, 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]);

  const filteredItemMenu = itemMenu[0].filter(
    (item) => user.role.includes(item.role) || item.role === "all"
  );

  return (
    <List>
      {filteredItemMenu.map((item, index) => (
        <SidebarListItem
          item={item}
          dispatch={dispatch}
          key={item.key}
          handleDrawerToggle={handleDrawerToggle}
        />
      ))}
      {filteredItemMenu.length > 0 && <Divider />}
    </List>
  );
}
