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

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

const _ResponsiveButton = forwardRef<Button, ResponsiveButtonProps>(
  (props, ref) => {
    const {
      dataHook,
      as,
      icon,
      children,
      state,
      shouldShrink: shouldShrinkProp = true,
      ...rest
    } = props;

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

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

    const { responsiveDisabled } = responsive;
    const isBmHarmonyTheme = useBmHarmonyTheme();

    const shouldShrink = responsiveDisabled
      ? shouldShrinkProp
      : state._shouldShrink;

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

export const ResponsiveButton = observer(_ResponsiveButton);
