import * as React from 'react';

import { Button } from '../../button';
import type { ButtonProps } from '../../button';
import { styled } from '@mui/material/styles';

import type { Theme } from '../../@styles/theme-provider';

type StyledToggleButtonProps = Pick<ToggleButtonProps, 'selected'>;

const StyledToggleButton = styled(Button, {
  name: 'ToggleButton',
  slot: 'Root',
  shouldForwardProp: prop => prop !== 'selected'
})<StyledToggleButtonProps>(({ selected, theme }: StyledToggleButtonProps & { theme: Theme }) => ({
  border: 'none',
  '& .MuiButton-startIcon': {
    marginRight: theme.spacing(0.5)
  },
  '& .MuiButton-endIcon': {
    marginLeft: theme.spacing(0.5)
  },
  ...(selected && {
    '&.MuiButton-root': {
      '&, &:hover, &:focus': {
        backgroundColor: theme.palette.secondary[700],
        color: theme.palette.common.white
      }
    }
  })
}));

export type ToggleButtonProps = Omit<
  ButtonProps,
  'color' | 'customSize' | 'disabled' | 'size' | 'value'
> & {
  /**
   * The value to associate with the button when selected in a ToggleButtonGroup.
   */
  value: string;
  /**
   * If `true`, the toggle button is disabled.
   * @default false
   */
  disabled?: boolean;
  /**
   * If `true`, the button is rendered in an active state.
   * @default false
   */
  selected?: boolean;
  /**
   * The callback is fired when the value changes.
   * @param {React.MouseEvent<HTMLElement>} event The event source of the callback.
   * @param value Value of the selected button.
   */
  onChange?: (event: React.MouseEvent<HTMLElement>, value: ButtonProps['value']) => void;
  /**
   * The callback is fired when the button is clicked.
   * @param {React.MouseEvent<HTMLElement>} event The event source of the callback.
   * @param value Value of the selected button.
   */
  onClick?: (event: React.MouseEvent<HTMLElement>, value: ButtonProps['value']) => void;
};

const ToggleButton = React.forwardRef(function (
  props: ToggleButtonProps,
  ref: React.Ref<HTMLButtonElement>
) {
  const { disabled = false, selected = false, value, onChange, onClick, ...otherProps } = props;

  const handleChange = (event: React.MouseEvent<HTMLElement>) => {
    if (onClick) {
      onClick(event, value);
      if (event.defaultPrevented) {
        return;
      }
    }

    if (onChange) {
      onChange(event, value);
    }
  };

  return (
    <StyledToggleButton
      ref={ref}
      data-testid="toggleButton"
      aria-pressed={selected}
      color="third"
      disabled={disabled}
      selected={selected}
      size="small"
      value={value}
      onClick={handleChange}
      onChange={onChange}
      {...otherProps}
    />
  );
});

const m = React.memo(ToggleButton);
export { m as ToggleButton };
