import { __awaiter } from "tslib";
import classNames from 'classnames';
import React, { forwardRef, useImperativeHandle, useRef, useState } from 'react';
import { withNativeProps } from '../../utils/native-props';
import { isPromise } from '../../utils/validate';
import { mergeProps } from '../../utils/with-default-props';
import { useConfig } from '../config-provider';
import DotLoading from '../dot-loading';
const defaultProps = {
  color: 'default',
  fill: 'solid',
  block: false,
  loading: false,
  loadingIcon: React.createElement(DotLoading, {
    color: 'currentColor'
  }),
  type: 'button',
  shape: 'default',
  size: 'middle'
};
export const Button = forwardRef((p, ref) => {
  const props = mergeProps(defaultProps, p);
  const {
    getPrefixCls
  } = useConfig();
  const prefixCls = getPrefixCls('button', props.prefixCls);
  const [innerLoading, setInnerLoading] = useState(false);
  const nativeButtonRef = useRef(null);
  const loading = props.loading === 'auto' ? innerLoading : props.loading;
  const disabled = props.disabled || loading;
  useImperativeHandle(ref, () => ({
    get nativeElement() {
      return nativeButtonRef.current;
    }
  }));
  const handleClick = e => __awaiter(void 0, void 0, void 0, function* () {
    if (!props.onClick) return;
    const promise = props.onClick(e);
    if (isPromise(promise)) {
      try {
        setInnerLoading(true);
        yield promise;
        setInnerLoading(false);
      } catch (e) {
        setInnerLoading(false);
        throw e;
      }
    }
  });
  return withNativeProps(props, React.createElement("button", {
    ref: nativeButtonRef,
    type: props.type,
    form: props.form,
    onClick: handleClick,
    className: classNames(prefixCls, {
      [`${prefixCls}-${props.color}`]: props.color,
      [`${prefixCls}-block`]: props.block,
      [`${prefixCls}-disabled`]: disabled,
      [`${prefixCls}-fill-outline`]: props.fill === 'outline',
      [`${prefixCls}-fill-none`]: props.fill === 'none',
      [`${prefixCls}-mini`]: props.size === 'mini',
      [`${prefixCls}-small`]: props.size === 'small',
      [`${prefixCls}-large`]: props.size === 'large',
      [`${prefixCls}-loading`]: loading
    }, `${prefixCls}-shape-${props.shape}`),
    disabled: disabled,
    onMouseDown: props.onMouseDown,
    onMouseUp: props.onMouseUp,
    onTouchStart: props.onTouchStart,
    onTouchEnd: props.onTouchEnd
  }, loading ? React.createElement("div", {
    className: `${prefixCls}-loading-wrapper`
  }, props.loadingIcon, props.loadingText) : React.createElement("span", null, props.children)));
});