import { Button, ButtonProps, TooltipProps } from '@wix/design-system';
import React, { forwardRef, useCallback } from 'react';
import { DisabledTooltip } from '../DisabledTooltip';

export type BulkActionButtonProps = ButtonProps & {
  tooltipText?: string;
  tooltipProps?: Partial<TooltipProps>;
};

export const BulkActionButton = forwardRef<HTMLButtonElement, BulkActionButtonProps>(
  (props, ref) => {
    const { tooltipText, tooltipProps, ...rest } = props;

    const setRef = useCallback(
      (element: HTMLElement | null) => {
        if (!ref) {
          return;
        }
        const buttonEl =
          (element?.querySelector('button') as HTMLButtonElement | null) ?? null;
        if (typeof ref === 'function') {
          ref(buttonEl);
        } else {
          (ref as React.MutableRefObject<HTMLButtonElement | null>).current =
            buttonEl;
        }
      },
      [ref],
    );

    return (
      <div ref={setRef} style={{ display: 'contents' }}>
        <DisabledTooltip
          content={tooltipText}
          dataHook="bulk-action-button-tooltip"
          {...tooltipProps}
        >
          <Button
            dataHook="bulk-action-button"
            skin="standard"
            priority="secondary"
            {...rest}
          />
        </DisabledTooltip>
      </div>
    );
  },
);

BulkActionButton.displayName = 'BulkActionButton';
