import { memo, useCallback } from 'react';
import clsx from 'clsx';

import MuiIconButton from '@mui/material/IconButton';

import { Tooltip } from '../@popovers/tooltip';
import { CustomIcon } from '../custom-icon';

import { MenuItemActionIconProps, MenuItemProps } from './types';

const MenuItemActionIcon = (
  props: MenuItemActionIconProps & {
    menuItemProps: Pick<MenuItemProps, 'name' | 'value' | 'styles'>;
  }
) => {
  const {
    iconSrc,
    menuItemProps: { name, value, styles },
    handleClick,
    tooltipText,
    ...iconButtonProps
  } = props;

  const handleIconButtonClick = useCallback(
    event => {
      event.stopPropagation();
      iconButtonProps.onClick?.(event);
      handleClick?.(name, value)?.(event);
    },
    [handleClick, iconButtonProps, name, value]
  );

  const button = (
    <MuiIconButton
      size="small"
      {...iconButtonProps}
      className={clsx(
        styles?.menuItemActionIcon,
        handleClick && styles?.menuItemActionIconClickable,
        iconButtonProps.className
      )}
      onClick={handleIconButtonClick}
    >
      <CustomIcon className={styles?.icon} color="inherit" src={iconSrc} />
    </MuiIconButton>
  );

  return tooltipText ? (
    <Tooltip title={tooltipText} placement="top" disableInteractive>
      {button}
    </Tooltip>
  ) : (
    button
  );
};

export default memo(MenuItemActionIcon);
