import React from 'react';
import cx from 'classnames';
import { LoaderIcon } from '../../icons/LoaderIcon';
import { defaultProps, sizes } from './.shared/common';
import type { ButtonProps } from './.shared/types';

function ButtonBase({
  children,
  className,
  size,
  connectedLeft,
  connectedRight,
  loading,
  loaderRight,
  loaderClassName,
  success,
  ...rest
}: ButtonProps) {
  const classes = cx('button-base', className, {
    'button-base-connected-r': connectedRight,
    'button-base-connected-l': connectedLeft,

    'button-base-md': size && size === sizes.md,
    'button-base-sm': size && size === sizes.sm,
    'button-base-xs': size && size === sizes.xs,
    'button-base-success': success,
  });

  if (typeof children === 'function') {
    return children(classes);
  }

  return (
    <button className={classes} {...rest}>
      {loading && !loaderRight && (
        <LoaderIcon className={`pr-2 ${loaderClassName}`} collapse />
      )}

      {children}

      {loading && loaderRight && (
        <LoaderIcon className={`pl-2 ${loaderClassName}`} collapse />
      )}
    </button>
  );
}

ButtonBase.defaultProps = {
  ...defaultProps,
  disabled: false,
};

ButtonBase.sizes = sizes;

export { ButtonBase };
