import { forwardRef } from 'react';

import IconButton, { type IconButtonProps } from '@mui/material/IconButton';

import Tooltip from '../../../Tooltip';

export type ActionButtonProps = {
  title: string;
  icon: React.ReactNode;
  onClick: () => void;
  isActive: boolean;
  disabled?: boolean;
  children?: React.ReactNode;
  sx?: IconButtonProps['sx'];
};

const ActionButton = (
  { title, icon, onClick, isActive, disabled, children, sx }: ActionButtonProps,
  ref: React.Ref<HTMLButtonElement>,
) => {
  const iconButton = (
    <IconButton
      ref={ref}
      disabled={disabled}
      onClick={onClick}
      sx={{
        height: 36,
        width: 36,
        borderRadius: 1,
        color: theme => theme.palette.new.text.neutral.default,
        transitionProperty: 'transform, color, background, opacity',
        transitionDuration: '125ms',
        transitionTimingFunction: 'ease-in-out',
        '&:hover': {
          transform: 'scale(1.1)',
        },
        '&:active': {
          transform: 'scale(0.9)',
        },
        '& svg': {
          stroke: theme => theme.palette.new.text.neutral.default,
        },
        ...(isActive && {
          backgroundColor: theme =>
            theme.palette.new.action.background.neutral.hover,
          color: theme => theme.palette.new.text.neutral.brand,
          transform: 'scale(0.9)',
          '&:hover': {
            transform: 'scale(0.9)',
          },
        }),
        ...(disabled && {
          opacity: 0.5,
          cursor: 'not-allowed',
        }),
        ...sx,
      }}
    >
      {children}
      {icon}
    </IconButton>
  );

  const actionButton = disabled ? <span>{iconButton}</span> : iconButton;

  return (
    <Tooltip
      description={title}
      direction="top"
      delay={100}
    >
      {actionButton}
    </Tooltip>
  );
};

export default forwardRef(ActionButton);
