import React, { useState, useEffect } from "react";
import {
  Drawer,
  List,
  ListItem,
  ListItemIcon,
  ListItemText,
  IconButton,
  Box,
  Accordion,
  AccordionSummary,
  AccordionDetails,
} from "@mui/material";
import PropTypes from "prop-types";
import { Link, useLocation } from "react-router-dom";
import {
  ChevronLeft as ChevronLeftIcon,
  ChevronRight as ChevronRightIcon,
  ExpandMore,
  Dashboard,
  Analytics,
  History,
  Summarize,
  Group,
  PeopleOutline,
  ManageAccounts,
  AssignmentInd,
  Description,
  Settings,
} from "@mui/icons-material";
import { useUser } from "../context/UserContext.js";
import "../pages/Dashboard.css";
import { permissionTypes } from "../constants/userConstants.js";

function CustomDrawer({ open, handleDrawerToggle }) {
  const location = useLocation();
  const [expandedAccordion, setExpandedAccordion] = useState(null);
  const [isSubMenuItemSelected, setIsSubMenuItemSelected] = useState(false);
  const { permissions } = useUser();

  useEffect(() => {
    setIsSubMenuItemSelected(location.pathname.includes("monitoring"));
  }, [location.pathname]);

  if (!permissions) {
    return;
  }

  const handleAccordionChange = (panel) => (event, isExpanded) => {
    if (!open && !isExpanded) {
      handleDrawerToggle();
    } else if (!open && isExpanded) {
      handleDrawerToggle();
      setExpandedAccordion(isExpanded ? panel : null);
    } else {
      setExpandedAccordion(isExpanded ? panel : null);
    }
  };

  const getIcon = (icon) => {
    switch (icon) {
      case "DashboardIcon":
        return <Dashboard />;
      case "HistoryIcon":
        return <History />;
      case "SummarizeIcon":
        return <Summarize />;
      case "GroupIcon":
        return <Group />;
      case "PeopleOutlineIcon":
        return <PeopleOutline />;
      case "ManageAccountsIcon":
        return <ManageAccounts />;
      case "AssignmentIndIcon":
        return <AssignmentInd />;
      case "DescriptionIcon":
        return <Description />;
      case "SettingsIcon":
        return <Settings />;
      default:
        return <Dashboard />;
    }
  };

  const getClassValue = () => (isSubMenuItemSelected && !expandedAccordion) ||
      (isSubMenuItemSelected && !open)
      ? "submenu-shell selected-menu-item "
      : "submenu-shell transparent-menu-item";

  return (
    <Drawer
      variant="permanent"
      anchor="left"
      open={open}
      sx={{
        width: open ? 250 : 60,
        flexShrink: 0,
        whiteSpace: "nowrap",
        transition: "width 0.3s",
        "& .MuiDrawer-paper": {
          width: open ? 250 : 60,
          overflowX: "hidden",
          transition: "width 0.3s",
        },
      }}
      className="sidebar"
    >
      <Box
        sx={{
          display: "flex",
          alignItems: "center",
          justifyContent: "flex-end",
          padding: "8px",
        }}
      >
        <IconButton onClick={handleDrawerToggle}>
          {open ? <ChevronLeftIcon /> : <ChevronRightIcon />}
        </IconButton>
      </Box>
  
      <List className="accordionHover">
        {permissions?.filter(p => p.ShowInMenu).map((item, index) => {
          const key = item.MenuName || item.Menu_Name || index;
          const isAccordion = !!item.SubMenuItems;
          const isExpanded = expandedAccordion == `panel-${index}`;
  
          if (!isAccordion) {
            const isActive = location.pathname === item.Path;
            const menuClass = isActive ? "selected-menu-item" : "transparent-menu-item";
  
            return (
              <ListItem
                key={key}
                className={menuClass}
                component={Link}
                to={item.Path}
              >
                <ListItemIcon className="sidebar-icons">
                  {getIcon(item.Icon)}
                </ListItemIcon>
                {open && (
                  <ListItemText
                    className="sidebar-text"
                    primary={item.Menu_Name}
                  />
                )}
              </ListItem>
            );
          }
  
          return (
            <Accordion
              key={key}
              style={{
                boxShadow: "none",
                position: "absolute",
                backgroundColor: "transparent",
              }}
              expanded={isExpanded}
              onChange={handleAccordionChange(`panel-${index}`)}
            >
              <AccordionSummary
                className={getClassValue()}
                style={{
                  maxHeight: "45px",
                  width: "250px",
                  minHeight: "0px",
                }}
                expandIcon={
                  <ExpandMore
                    style={{
                      display: open ? "block" : "none",
                      color:
                        !expandedAccordion && isSubMenuItemSelected
                          ? "#fff"
                          : "#211E1E",
                    }}
                  />
                }
                aria-controls={`panel-${index}-content`}
                id={`panel-${index}-header`}
              >
                <ListItemIcon className="sidebar-icons">
                  <Analytics />
                </ListItemIcon>
                {open && (
                  <ListItemText
                    className="sidebar-text"
                    primary={item.MenuName}
                  />
                )}
              </AccordionSummary>
  
              <AccordionDetails
                style={{
                  padding: "0px",
                  display: open ? "block" : "none",
                }}
              >
                <List className="submenu">
                  {item.SubMenuItems
                    .filter(sub => Number.parseInt(sub.Permission_Id) !== permissionTypes[2].key)
                    .map((subItem) => {
                      const isActive = location.pathname === subItem.Path;
                      const menuClass = isActive
                        ? "selected-menu-item"
                        : "transparent-menu-item";
  
                      return (
                        <ListItem
                          key={subItem.SubFeatureName}
                          style={{ color: "#211E1E", paddingLeft: "38px" }}
                          className={menuClass}
                          component={Link}
                          to={subItem.Path}
                        >
                          <li style={{ listStyleType: "disc" }}>
                            <ListItemText primary={subItem.SubFeatureName} />
                          </li>
                        </ListItem>
                      );
                    })}
                </List>
              </AccordionDetails>
            </Accordion>
          );
        })}
      </List>
    </Drawer>
  );
}

CustomDrawer.propTypes = {
  open: PropTypes.bool.isRequired,
  handleDrawerToggle: PropTypes.func.isRequired,
};

export default CustomDrawer;
