import { useRef, useState } from 'react';

import Menu from '@design-system/Menu';
import MenuItem from '@design-system/Menu/components/MenuItem';
import { Button, useTheme } from '@mui/material';
import { IconChevronDown } from '@tabler/icons-react';

import { type MenuActionButtonProps, type MenuOption } from './types';

const MenuActionButton = ({
  icon,
  options,
  onOptionSelect,
  selectedOption,
  optionRenderer,
  ariaLabel,
  ariaControls,
}: MenuActionButtonProps) => {
  const anchorRef = useRef<HTMLButtonElement>(null);
  const theme = useTheme();

  const [open, setOpen] = useState(false);

  const openMenu = () => setOpen(true);

  const handleClickOption =
    (option: MenuOption) => (event: React.MouseEvent<HTMLLIElement>) => {
      option.onClick?.(event, option);
      if (option.value) onOptionSelect?.(option.value);
      setOpen(false);
    };

  return (
    <>
      <Menu
        open={open}
        anchorEl={anchorRef.current}
        onClose={() => setOpen(false)}
        sx={{ minWidth: '200px' }}
      >
        {options?.map(option => (
          <MenuItem
            key={option.label}
            onClick={handleClickOption(option)}
            selected={selectedOption === option.value}
          >
            {optionRenderer?.(option) ?? option.label}
          </MenuItem>
        ))}
      </Menu>
      <Button
        focusRipple
        onClick={openMenu}
        variant="secondary"
        sx={{
          color: theme.palette.new.text.neutral.default,
          borderColor: theme.palette.new.border.neutral.default,
          '& svg': {
            stroke: theme.palette.new.text.neutral.default,
          },
        }}
        ref={anchorRef}
        aria-label={ariaLabel}
        aria-controls={ariaControls}
        aria-expanded={open ? 'true' : undefined}
        aria-haspopup="true"
        endIcon={<IconChevronDown />}
      >
        {icon}
        {!icon && options.find(({ value }) => value === selectedOption)?.label}
      </Button>
    </>
  );
};

export default MenuActionButton;
