import { ExpandLess, ExpandMore } from "@mui/icons-material";
import { Collapse, List, ListItem, ListItemButton, ListItemIcon, ListItemText, Stack } from "@mui/material";
import Link from "next/link";
import SidebarBadge from "./SidebarBadge";
import SidebarSubitems from "./SidebarSubitems";

const SidebarListItems = ({ menuItem, dispatch }) => {
    return (
        <>
            <ListItem disablePadding divider>
                <ListItemButton
                    sx={{ p: 0.5 }}
                    disableGutters
                    selected={menuItem.selected}
                    component={menuItem.type === "page" ? Link : null}
                    href={menuItem.type === "page" ? menuItem.route : null}
                    onClick={() => {
                        if (menuItem.type !== "page") {
                            dispatch({ type: "COLLAPSE_MENU", id: menuItem.id });
                        }
                    }}
                >
                    <ListItemIcon
                        sx={{
                            minWidth: 0,
                            justifyContent: "center",
                            color: "primary.main",
                            width: 40,
                            height: 24,
                        }}
                    >
                        {menuItem.icon}
                    </ListItemIcon>
                    <ListItemText primary={menuItem.label} />
                    {menuItem.badges && (
                        <Stack direction={"row"} sx={{ px: 0.5 }} spacing={0.5}>
                            {menuItem.badges.map((badge, i) => (
                                <SidebarBadge
                                    chipProps={{ color: badge.color || "primary" }}
                                    key={badge.key}
                                    badge={badge.key}
                                />
                            ))}
                        </Stack>
                    )}
                    {menuItem.hasSubitems ? menuItem.showSubitems ? <ExpandLess /> : <ExpandMore /> : null}
                </ListItemButton>
            </ListItem>
            <Collapse in={menuItem.showSubitems} timeout="auto" mountOnEnter={true} unmountOnExit={true}>
                {menuItem.hasSubitems ? (
                    <List
                        disablePadding
                        dense
                        sx={{
                            background: "#00000008",
                        }}
                    >
                        {menuItem.Subitems.map((subitem, index) => {
                            return <SidebarSubitems key={index} dispatch={dispatch} subitem={subitem} />;
                        })}
                    </List>
                ) : null}
            </Collapse>
        </>
    );
};
export default SidebarListItems;
