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';

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 shouldShrink = responsiveDisabled
      ? shouldShrinkProp
      : state._shouldShrink;

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

export const ResponsiveButton = observer(_ResponsiveButton);
