import { type MouseEvent, useState } from 'react';

import { IconDotsVertical, type TablerIcon } from '@material-hu/icons/tabler';
import IconButton from '@material-hu/mui/IconButton';

import HuMenu from '@material-hu/components/design-system/Menu';

import GoalCardMenuItem from './GoalCardMenuItem';

export type GoalCardMenuOption = {
  id: string;
  icon: TablerIcon;
  title: string;
  onClick: () => void;
  showChevron?: boolean;
};

export type GoalCardMenuProps = {
  menuId: string;
  label: string;
  options: GoalCardMenuOption[];
};

const GoalCardMenu = ({ menuId, label, options }: GoalCardMenuProps) => {
  const [anchorEl, setAnchorEl] = useState<HTMLButtonElement | null>(null);
  const open = Boolean(anchorEl);

  const handleOpen = (event: MouseEvent<HTMLButtonElement>) => {
    event.stopPropagation();
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  return (
    <>
      <IconButton
        onClick={handleOpen}
        aria-label={label}
        aria-controls={open ? menuId : undefined}
        aria-expanded={open ? 'true' : 'false'}
        aria-haspopup="true"
      >
        <IconDotsVertical />
      </IconButton>
      <HuMenu
        id={menuId}
        anchorEl={anchorEl}
        open={open}
        onClose={handleClose}
        position="right"
      >
        {options.map(option => (
          <GoalCardMenuItem
            key={option.id}
            icon={option.icon}
            title={option.title}
            onClick={option.onClick}
            onClose={handleClose}
            showChevron={option.showChevron}
          />
        ))}
      </HuMenu>
    </>
  );
};

export default GoalCardMenu;
