import React from "react";
import { SxProps, Theme } from "@mui/material/styles";
import List from "@mui/material/List";
import ListItem from "@mui/material/ListItem";
import ListItemButton from "@mui/material/ListItemButton";
import ListItemIcon from "@mui/material/ListItemIcon";
import ListItemText from "@mui/material/ListItemText";
import Badge from "@mui/material/Badge";
import { ExpandLess, ExpandMore } from "@mui/icons-material";
import { Collapse, Divider, Tooltip } from "@mui/material";

type MenuItemProps = {
  open: boolean;
  icon: React.ReactNode;
  label: string;
  onClick?: () => void;
  subMenus?: MenuItemProps[];
  sx?: SxProps<Theme>;
};

const MenuItem: React.FC<MenuItemProps> = ({ open, icon, label, onClick, subMenus, sx }) => {
  const [openSubMenu, setOpenSubMenu] = React.useState(false);

  const handleSubMenuToggle = () => {
    setOpenSubMenu(!openSubMenu);
  };

  return (
    <>
      <ListItem disablePadding sx={{ display: "block" }}>
        <Tooltip title={open ? undefined : label} placement="right" arrow>
          <ListItemButton
            sx={{
              minHeight: 48,
              justifyContent: open ? "initial" : "center",
              px: 2.5,
              ...sx
            }}
            onClick={onClick ? onClick : handleSubMenuToggle}
          >
            <ListItemIcon
              sx={{
                minWidth: 0,
                mr: open ? 3 : "auto",
                justifyContent: "center"
              }}
            >
              {open || !subMenus ? (
                icon
              ) : (
                <Badge badgeContent={openSubMenu ? <ExpandLess fontSize="small" /> : <ExpandMore fontSize="small" />}>
                  {icon}
                </Badge>
              )}
            </ListItemIcon>
            <ListItemText
              primary={label}
              sx={{ opacity: open ? 1 : 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}
            />
            {subMenus && open && (
              <ListItemIcon sx={{ minWidth: 0, ml: "auto" }}>
                {openSubMenu ? <ExpandLess /> : <ExpandMore />}
              </ListItemIcon>
            )}
          </ListItemButton>
        </Tooltip>
      </ListItem>
      {subMenus && (
        <Collapse in={openSubMenu} timeout="auto" unmountOnExit>
          <List component="div" disablePadding>
            {subMenus.map((subItem, index) => (
              <React.Fragment key={index}>
                <MenuItem key={index} {...subItem} sx={{ marginLeft: subItem.open ? 2 : 0 }} />
                {index === subMenus.length - 1 && <Divider />}
              </React.Fragment>
            ))}
          </List>
        </Collapse>
      )}
    </>
  );
};

export default MenuItem;
