import * as React from "react";
import { styled } from "@mui/material/styles";
import MuiDrawer from "@mui/material/Drawer";
import List from "@mui/material/List";
import { useDispatch, useSelector } from "react-redux";
import { getUserProfile } from "../../features/authentication/services/getUserProfile";
import { useUserProfile } from "../../features/authentication/hooks/useUserProfile";
import { SidebarHeader } from "./components/SidebarHeader";
import { LogoutButton } from "./components/LogoutButton";
import { RoleAccordion } from "./components/RoleAccordion";
import { RoleMenuRenderer } from "./components/RoleMenuRenderer";
import { useSidebarState } from "./hooks/useSidebarState";
import { useResponsiveSidebar } from "./hooks/useResponsiveSidebar";
import { getMenuItemsByRole } from "./constants/roleMenuConfigs";

const drawerWidth = 280;

const openedMixin = (theme) => ({
  width: drawerWidth,
  transition: theme.transitions.create("width", {
    easing: theme.transitions.easing.sharp,
    duration: theme.transitions.duration.enteringScreen,
  }),
  overflowX: "hidden",
});

const closedMixin = (theme) => ({
  transition: theme.transitions.create("width", {
    easing: theme.transitions.easing.sharp,
    duration: theme.transitions.duration.leavingScreen,
  }),
  overflowX: "hidden",
  width: `calc(${theme.spacing(7)} + 1px)`,
  [theme.breakpoints.up("sm")]: {
    width: `calc(${theme.spacing(8)} + 1px)`,
  },
});

const Drawer = styled(MuiDrawer, {
  shouldForwardProp: (prop) => prop !== "open",
})(({ theme, open }) => ({
  width: drawerWidth,
  flexShrink: 0,
  whiteSpace: "nowrap",
  boxSizing: "border-box",
  position: "absolute",
  ...(open && {
    ...openedMixin(theme),
    "& .MuiDrawer-paper": openedMixin(theme),
  }),
  ...(!open && {
    ...closedMixin(theme),
    "& .MuiDrawer-paper": closedMixin(theme),
  }),
}));

export const Sidebar = () => {
  const dispatch = useDispatch();
  const [role, userProfile] = useUserProfile();
  const roles = [...role];
  const { slaughterPermissionState } = useSelector(
    (item) => item.slaughterSlice
  );

  const {
    open,
    setOpen,
    expandedItems,
    openSub,
    closeSidebar,
    handleAccordionChange,
    toggleSubMenu,
  } = useSidebarState();

  const { isMobile } = useResponsiveSidebar();

  React.useEffect(() => {
    if (Array.isArray(role)) {
      roles.sort();
    }
    dispatch(getUserProfile());
  }, [dispatch, role, roles]);

  return (
    <Drawer
      id="sidebar"
      onMouseEnter={() => {
        if (!isMobile) {
          setOpen(true);
        }
      }}
      onMouseLeave={() => {
        if (!isMobile) {
          setOpen(false);
        }
      }}
      variant="permanent"
      open={open}
      sx={{
        display: {
          xs: open ? "block" : "none",
          sm: open ? "block" : "none",
          md: "block",
        },
        zIndex: (theme) => theme.zIndex.drawer + 11,
      }}
    >
      <List component="nav">
        <SidebarHeader
          userProfile={userProfile}
          open={open}
          onClose={closeSidebar}
        />

        {roles.map((userRole, i) => {
          const menuConfig = getMenuItemsByRole(userRole, {
            slaughterPermissionState,
          });
          const isExpanded = expandedItems.includes(i);

          // Skip rendering if no menu items
          if (
            (!menuConfig.collapsibleSections ||
              menuConfig.collapsibleSections.length === 0) &&
            (!menuConfig.regularItems || menuConfig.regularItems.length === 0)
          ) {
            return null;
          }

          return (
            <RoleAccordion
              key={i}
              role={userRole}
              index={i}
              open={open}
              isExpanded={isExpanded}
              onToggle={() => handleAccordionChange(i)}
            >
              <RoleMenuRenderer
                menuConfig={menuConfig}
                open={open}
                openSub={openSub}
                onToggleSub={toggleSubMenu}
                onClose={closeSidebar}
              />
            </RoleAccordion>
          );
        })}

        <LogoutButton open={open} onClose={closeSidebar} />
      </List>
    </Drawer>
  );
};
