import { ExpandLess, ExpandMore, Link } from "@mui/icons-material";
import {
  Button,
  Divider,
  ListItemIcon,
  ListItemText,
  Menu,
  MenuItem,
  Stack,
} from "@mui/material";
import NextLink from "next/link";
import { useState } from "react";

const HeaderMenu = ({ menu }) => {
  const [anchorEl, setAnchorEl] = useState(null);
  const open = Boolean(anchorEl);

  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };
  const handleClose = () => {
    setAnchorEl(null);
  };

  return (
    <Stack sx={{ mr: 0.5 }}>
      <Button
        color="inherit"
        aria-haspopup="true"
        aria-expanded={open ? "true" : undefined}
        onClick={handleClick}
        endIcon={open ? <ExpandLess /> : <ExpandMore />}
      >
        {menu.title}
      </Button>
      <Menu anchorEl={anchorEl} open={open} onClose={handleClose}>
        {menu.subMenu.flatMap((subMenu, index) => [
          ...subMenu.map((sub) => (
            <MenuItem
              component={NextLink}
              href={sub.href}
              key={sub.title}
              onClick={handleClose}
            >
              <ListItemIcon>
                <Link fontSize="small" />
              </ListItemIcon>
              <ListItemText>{sub.title}</ListItemText>
            </MenuItem>
          )),
          index < menu.subMenu.length - 1 && (
            <Divider key={`divider-${index}`} />
          ),
        ])}
      </Menu>
    </Stack>
  );
};

export default HeaderMenu;
