import type { ButtonHTMLAttributes, ReactNode } from 'react';
import { BusyRing } from './BusyRing';

export type IconButtonVariant = 'neutral' | 'add' | 'danger';

export interface IconButtonProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'title'> {
  label: string;
  icon: ReactNode;
  variant?: IconButtonVariant;
  loading?: boolean;
  tooltip?: string;
}

export function IconButton({
  label,
  icon,
  variant = 'neutral',
  loading = false,
  tooltip,
  className,
  disabled,
  ...props
}: IconButtonProps) {
  const tooltipText = tooltip === '' ? undefined : tooltip ?? label;
  const classes = [
    'ui-icon-button',
    `ui-icon-button--${variant}`,
    loading ? 'is-loading' : '',
    className ?? '',
  ].filter(Boolean).join(' ');

  return (
    <button
      {...props}
      type={props.type ?? 'button'}
      className={classes}
      aria-label={label}
      data-tooltip={tooltipText}
      disabled={disabled || loading}
      aria-busy={loading || undefined}
    >
      {loading ? <BusyRing /> : null}
      {icon}
    </button>
  );
}

