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

export interface ActionButtonProps {
  actionItem: ActionSubItemPrivate;
  suffixIcon?: ButtonProps['suffixIcon'];
  size?: ButtonProps['size'];
  priority?: ButtonProps['priority'];
  fullWidth?: ButtonProps['fullWidth'];
}

export function ActionButton(props: ActionButtonProps) {
  const { actionItem, suffixIcon, size, priority, fullWidth } = props;
  const { tooltip, prefixIcon, label, onClick, dataHook, disabled, ref } =
    actionItem;

  const setRef = useCallback(
    (element: HTMLElement | null) => {
      if (!element || !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={{ width: '100%' }}>
      <DisabledTooltip content={tooltip} dataHook={`${dataHook}-tooltip`}>
        <Button
          skin="standard"
          priority={priority}
          size={size}
          prefixIcon={prefixIcon}
          ellipsis
          onClick={onClick}
          dataHook={dataHook}
          disabled={disabled}
          suffixIcon={suffixIcon}
          fullWidth={fullWidth}
        >
          {label}
        </Button>
      </DisabledTooltip>
    </div>
  );
}
