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

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

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

import { type ReviewDirection } from 'src/pages/dashboard/performance/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

export type ReviewerSelectionMenuProps = {
  directions: ReviewDirection[];
  onSelect: (direction: ReviewDirection) => void;
};

const MENU_ID = 'reviewer-selection-menu';

const ReviewerSelectionMenu = ({
  directions,
  onSelect,
}: ReviewerSelectionMenuProps) => {
  const { t } = useLokaliseTranslation('performance');
  const [anchorEl, setAnchorEl] = useState<HTMLButtonElement | null>(null);
  const isOpen = Boolean(anchorEl);
  const closeMenu = () => setAnchorEl(null);

  return (
    <>
      <IconButton
        aria-label="menu"
        aria-controls={isOpen ? MENU_ID : undefined}
        aria-haspopup="true"
        aria-expanded={isOpen ? 'true' : undefined}
        onClick={(event: MouseEvent<HTMLButtonElement>) =>
          setAnchorEl(event.currentTarget)
        }
      >
        <IconDotsVertical />
      </IconButton>
      <HuMenu
        id={MENU_ID}
        anchorEl={anchorEl}
        open={isOpen}
        onClose={closeMenu}
        position="right"
      >
        {directions.map(direction => (
          <MenuItem
            key={direction}
            onClick={() => {
              closeMenu();
              onSelect(direction);
            }}
            sx={{ whiteSpace: 'normal' }}
          >
            <Typography
              variant="globalS"
              fontWeight="fontWeightSemiBold"
            >
              {t('nominate_reviewers.reviewers_selection', {
                context: direction,
              })}
            </Typography>
          </MenuItem>
        ))}
      </HuMenu>
    </>
  );
};

export default ReviewerSelectionMenu;
