import {
  Box,
  Button,
  ButtonAsButtonProps,
  IconButton,
  IconElement,
  Tooltip,
} from '@wix/design-system';
import React from 'react';
import { observer } from 'mobx-react-lite';
import { useToolbarCollectionContext } from '../ToolbarCollectionContext';
import { ToolbarResponsivePriorityState } from '../../state/Toolbar/ToolbarResponsivePriorityState';
import { usePatternsTheme } from '../../themes/PatternsThemeProvider';

export type ResponsiveButtonProps = ButtonAsButtonProps<{
  dataHook?: string;
  icon?: IconElement;
  state: ToolbarResponsivePriorityState;
  shouldShrink?: boolean;
}>;

function _ResponsiveButton(props: ResponsiveButtonProps) {
  const {
    dataHook,
    as,
    icon,
    children,
    state,
    shouldShrink: shouldShrinkProp = true,
    ...rest
  } = props;

  const {
    sizes,
    toolbar: { button },
  } = usePatternsTheme();

  const {
    toolbar: { responsive },
  } = useToolbarCollectionContext();

  const { _nextToShrink, responsiveDisabled } = responsive;

  const shouldShrink = responsiveDisabled
    ? shouldShrinkProp
    : _nextToShrink._count >= state._count && state._shouldShrink;

  return shouldShrink ? (
    <Tooltip
      content={children}
      dataHook={dataHook ? `${dataHook}-tooltip` : undefined}
    >
      <Box direction="vertical" minWidth="30px">
        <IconButton
          {...rest}
          dataHook={dataHook}
          size={sizes.small}
          priority="secondary"
        >
          {icon}
        </IconButton>
      </Box>
    </Tooltip>
  ) : (
    <Button
      as={as}
      {...rest}
      dataHook={dataHook}
      size={sizes.small}
      priority="secondary"
      prefixIcon={icon}
      suffixIcon={button.suffix}
    >
      {children}
    </Button>
  );
}

export const ResponsiveButton = observer(_ResponsiveButton);
