import "core-js/modules/es.array.iterator.js";
import "core-js/modules/web.dom-collections.iterator.js";
import * as React from 'react';
import Button from '../button';
import { jsx as _jsx } from "react/jsx-runtime";
function convertLegacyProps(type) {
  if (type === 'danger') {
    return {
      danger: true
    };
  }
  return {
    type
  };
}
const ActionButton = props => {
  const clickedRef = React.useRef(false);
  const ref = React.useRef();
  const [loading, setLoading] = React.useState(false);
  React.useEffect(() => {
    let timeoutId;
    if (props.autoFocus) {
      const $this = ref.current;
      timeoutId = setTimeout(() => $this.focus());
    }
    return () => {
      if (timeoutId) {
        clearTimeout(timeoutId);
      }
    };
  }, []);
  const handlePromiseOnOk = returnValueOfOnOk => {
    const {
      closeModal
    } = props;
    if (!returnValueOfOnOk || !returnValueOfOnOk.then) {
      return;
    }
    setLoading(true);
    returnValueOfOnOk.then((...args) => {
      // It's unnecessary to set loading=false, for the Modal will be unmounted after close.
      // setState({ loading: false });
      closeModal(...args);
    }, e => {
      // Emit error when catch promise reject
      // eslint-disable-next-line no-console
      console.error(e);
      // See: https://github.com/ant-design/ant-design/issues/6183
      setLoading(false);
      clickedRef.current = false;
    });
  };
  const onClick = () => {
    const {
      actionFn,
      closeModal
    } = props;
    if (clickedRef.current) {
      return;
    }
    clickedRef.current = true;
    if (!actionFn) {
      closeModal();
      return;
    }
    let returnValueOfOnOk;
    if (actionFn.length) {
      returnValueOfOnOk = actionFn(closeModal);
      // https://github.com/ant-design/ant-design/issues/23358
      clickedRef.current = false;
    } else {
      returnValueOfOnOk = actionFn();
      if (!returnValueOfOnOk) {
        closeModal();
        return;
      }
    }
    handlePromiseOnOk(returnValueOfOnOk);
  };
  const {
    children,
    type,
    prefixCls,
    buttonProps
  } = props;
  return /*#__PURE__*/_jsx(Button, {
    ...convertLegacyProps(type),
    onClick: onClick,
    loading: loading,
    prefixCls: prefixCls,
    ...buttonProps,
    ref: ref,
    children: children
  });
};
export default ActionButton;