import React__default, { useContext, useState, useRef, useImperativeHandle, useCallback, useEffect } from "react";
import index from "../../../../../../number-precision@1.5.2/node_modules/number-precision/build/index.es.js";
import IconUp from "../../icon/react-icon/IconUp/index.js";
import IconDown from "../../icon/react-icon/IconDown/index.js";
import IconPlus from "../../icon/react-icon/IconPlus/index.js";
import IconMinus from "../../icon/react-icon/IconMinus/index.js";
import { isNumber } from "../_util/is.js";
import cs from "../_util/classNames.js";
import { ArrowDown, ArrowUp } from "../_util/keycode.js";
import { ConfigContext } from "../ConfigProvider/index.js";
import Input from "../Input/input.js";
import useMergeProps from "../_util/hooks/useMergeProps.js";
import omit from "../_util/omit.js";
import { toFixed, toSafeString } from "./utils.js";
import { jsx, jsxs, Fragment } from "../../../../../../@emotion_react@11.10.4_3toe27fv7etiytxb5kxc7fxaw4/node_modules/@emotion/react/jsx-runtime/dist/emotion-react-jsx-runtime.browser.esm.js";
var __assign = globalThis && globalThis.__assign || function() {
  __assign = Object.assign || function(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];
      for (var p in s)
        if (Object.prototype.hasOwnProperty.call(s, p))
          t[p] = s[p];
    }
    return t;
  };
  return __assign.apply(this, arguments);
};
var __rest = globalThis && globalThis.__rest || function(s, e) {
  var t = {};
  for (var p in s)
    if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
      t[p] = s[p];
  if (s != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
      if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
        t[p[i]] = s[p[i]];
    }
  return t;
};
var __read = globalThis && globalThis.__read || function(o, n) {
  var m = typeof Symbol === "function" && o[Symbol.iterator];
  if (!m)
    return o;
  var i = m.call(o), r, ar = [], e;
  try {
    while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
      ar.push(r.value);
  } catch (error) {
    e = {
      error
    };
  } finally {
    try {
      if (r && !r.done && (m = i["return"]))
        m.call(i);
    } finally {
      if (e)
        throw e.error;
    }
  }
  return ar;
};
index.enableBoundaryChecking(false);
var AUTO_CHANGE_INTERVAL = 200;
var AUTO_CHANGE_START_DELAY = 1e3;
var defaultProps = {
  max: Infinity,
  min: -Infinity,
  step: 1,
  mode: "embed",
  parser: function(input) {
    return input.replace(/[^\w\.-]+/g, "");
  }
};
function InputNumber(baseProps, ref) {
  var _a;
  var _b = useContext(ConfigContext), getPrefixCls = _b.getPrefixCls, ctxSize = _b.size, componentConfig = _b.componentConfig;
  var props = useMergeProps(baseProps, defaultProps, componentConfig === null || componentConfig === void 0 ? void 0 : componentConfig.InputNumber);
  var className = props.className, style = props.style, defaultValue = props.defaultValue, disabled = props.disabled, error = props.error, readOnly = props.readOnly, placeholder = props.placeholder, hideControl = props.hideControl, suffix = props.suffix, prefix = props.prefix, icons = props.icons, mode = props.mode, size = props.size, step = props.step, precision = props.precision, min = props.min, max = props.max, parser = props.parser, formatter = props.formatter, onBlur = props.onBlur, onFocus = props.onFocus, onChange = props.onChange, onKeyDown = props.onKeyDown, rest = __rest(props, ["className", "style", "defaultValue", "disabled", "error", "readOnly", "placeholder", "hideControl", "suffix", "prefix", "icons", "mode", "size", "step", "precision", "min", "max", "parser", "formatter", "onBlur", "onFocus", "onChange", "onKeyDown"]);
  var prefixCls = getPrefixCls("input-number");
  var mergedSize = size || ctxSize;
  var mergedPrecision = function() {
    if (isNumber(precision)) {
      var decimal = ("" + step).split(".")[1];
      var stepPrecision = decimal && decimal.length || 0;
      return Math.max(stepPrecision, precision);
    }
    return null;
  }();
  var _c = __read(useState("defaultValue" in props ? defaultValue : void 0), 2), innerValue = _c[0], setInnerValue = _c[1];
  var value = function() {
    var mergedValue = "value" in props ? props.value : innerValue;
    return typeof mergedValue === "string" && mergedValue !== "" ? +mergedValue : mergedValue;
  }();
  var _d = __read(useState(""), 2), inputValue = _d[0], setInputValue = _d[1];
  var _e = __read(useState(false), 2), isOutOfRange = _e[0], setIsOutOfRange = _e[1];
  var _f = __read(useState(false), 2), isUserInputting = _f[0], setIsUserInputting = _f[1];
  var isEmptyValue = value === "" || value === void 0 || value === null;
  var refAutoTimer = useRef(null);
  var refInput = useRef(null);
  var refHasOperateSincePropValueChanged = useRef(false);
  useImperativeHandle(ref, function() {
    return refInput.current;
  }, []);
  var setValue = function(newVal) {
    setInnerValue(newVal);
    var newValue = isNumber(+newVal) ? +newVal : void 0;
    if (newValue !== value) {
      onChange && onChange(newValue);
    }
  };
  var stop = function() {
    refAutoTimer.current && clearTimeout(refAutoTimer.current);
    refAutoTimer.current = null;
  };
  var getLegalValue = useCallback(function(changedValue) {
    var finalValue = Number(changedValue);
    if (!changedValue && changedValue !== 0) {
      finalValue = void 0;
    } else if (!isNumber(finalValue)) {
      finalValue = changedValue === "-" ? changedValue : "";
    }
    if (finalValue < min) {
      finalValue = min;
    }
    if (finalValue > max) {
      finalValue = max;
    }
    return isNumber(finalValue) ? isNumber(mergedPrecision) ? Number(toFixed(finalValue, mergedPrecision)) : finalValue : void 0;
  }, [min, max, mergedPrecision]);
  useEffect(function() {
    return function() {
      return stop();
    };
  }, []);
  useEffect(function() {
    refHasOperateSincePropValueChanged.current = false;
  }, [props.value]);
  useEffect(function() {
    var _isOutOfRange = isNumber(min) && value < min || isNumber(max) && value > max;
    if (_isOutOfRange && refHasOperateSincePropValueChanged.current) {
      setValue(getLegalValue(value));
    }
    setIsOutOfRange(_isOutOfRange);
  }, [min, max, value, getLegalValue]);
  var handleArrowKey = function(event, method, needRepeat) {
    if (needRepeat === void 0) {
      needRepeat = false;
    }
    event.persist();
    event.preventDefault();
    setIsUserInputting(false);
    if (disabled || readOnly) {
      return;
    }
    var finalValue = min === -Infinity ? 0 : min;
    if (!isEmptyValue) {
      finalValue = index[method](value, step);
    }
    setValue(getLegalValue(finalValue));
    refInput.current && refInput.current.focus();
    if (needRepeat) {
      var isFirstRepeat = refAutoTimer.current === null;
      refAutoTimer.current = setTimeout(function() {
        return event.target.dispatchEvent(event.nativeEvent);
      }, isFirstRepeat ? AUTO_CHANGE_START_DELAY : AUTO_CHANGE_INTERVAL);
    }
  };
  var getDisplayInputValue = function() {
    var _value;
    if (isUserInputting) {
      _value = inputValue;
    } else if (isNumber(value) && isNumber(mergedPrecision)) {
      _value = toFixed(value, mergedPrecision);
    } else if (value == null) {
      _value = "";
    } else {
      _value = toSafeString(value);
    }
    return formatter ? formatter(_value) : _value;
  };
  var inputEventHandlers = {
    onChange: function(value2) {
      setIsUserInputting(true);
      var targetValue = value2.trim().replace(/。/g, ".");
      targetValue = parser ? parser(targetValue) : targetValue;
      if (isNumber(+targetValue) || targetValue === "-" || !targetValue || targetValue === ".") {
        var formatValue = getLegalValue(targetValue);
        setInputValue(targetValue);
        setValue(formatValue);
      }
    },
    onKeyDown: function(e) {
      e.stopPropagation();
      var key = e.key;
      if (key === ArrowDown.key) {
        handleArrowKey(e, "minus");
      } else if (key === ArrowUp.key) {
        handleArrowKey(e, "plus");
      }
      stop();
      onKeyDown && onKeyDown(e);
    },
    onFocus: function(e) {
      var _a2, _b2;
      refHasOperateSincePropValueChanged.current = true;
      setInputValue((_b2 = (_a2 = refInput.current) === null || _a2 === void 0 ? void 0 : _a2.dom) === null || _b2 === void 0 ? void 0 : _b2.value);
      onFocus && onFocus(e);
    },
    onBlur: function(e) {
      setValue(getLegalValue(value));
      setIsUserInputting(false);
      onBlur && onBlur(e);
    }
  };
  var getControlButtonEventsHandlers = function(method) {
    return readOnly ? {} : {
      onMouseDown: function(e) {
        return handleArrowKey(e, method, true);
      },
      onMouseLeave: stop,
      onMouseUp: stop
    };
  };
  var shouldRenderButton = !hideControl && mode === "button";
  var shouldRenderLayer = !hideControl && !readOnly && mode === "embed";
  var renderStepButton = function(method, icon) {
    var _a2;
    return /* @__PURE__ */ jsx("div", {
      ...__assign({
        className: cs(prefixCls + "-step-button", (_a2 = {}, _a2[prefixCls + "-step-button-disabled"] = disabled || (method === "plus" ? +value >= +max : +value <= +min), _a2))
      }, getControlButtonEventsHandlers(method)),
      children: icon
    });
  };
  return /* @__PURE__ */ jsx(Input, {
    ...__assign({
      _ignorePropsFromGlobal: true,
      role: "spinbutton",
      "aria-valuemax": max,
      "aria-valuemin": min,
      "aria-valuenow": value
    }, omit(rest, ["allowClear"]), inputEventHandlers, {
      style,
      className: cs(prefixCls, prefixCls + "-mode-" + mode, prefixCls + "-size-" + mergedSize, (_a = {}, _a[prefixCls + "-readonly"] = readOnly, _a[prefixCls + "-illegal-value"] = !isEmptyValue && isOutOfRange, _a), className),
      ref: refInput,
      size: mergedSize,
      error,
      disabled,
      readOnly,
      value: getDisplayInputValue(),
      placeholder,
      prefix: prefix && /* @__PURE__ */ jsx("div", {
        className: prefixCls + "-prefix",
        children: prefix
      }),
      suffix: /* @__PURE__ */ jsxs(Fragment, {
        children: [shouldRenderLayer && /* @__PURE__ */ jsxs("div", {
          className: prefixCls + "-step-layer",
          children: [renderStepButton("plus", icons && icons.up ? icons.up : /* @__PURE__ */ jsx(IconUp, {})), renderStepButton("minus", icons && icons.down ? icons.down : /* @__PURE__ */ jsx(IconDown, {}))]
        }), suffix && /* @__PURE__ */ jsx("div", {
          className: prefixCls + "-suffix",
          children: suffix
        })]
      }),
      addBefore: shouldRenderButton && renderStepButton("minus", icons && icons.minus ? icons.minus : /* @__PURE__ */ jsx(IconMinus, {})),
      addAfter: shouldRenderButton && renderStepButton("plus", icons && icons.plus ? icons.plus : /* @__PURE__ */ jsx(IconPlus, {}))
    })
  });
}
var InputNumberComponent = React__default.forwardRef(InputNumber);
InputNumberComponent.displayName = "InputNumber";
const InputNumber$1 = InputNumberComponent;
export {
  InputNumber$1 as default
};
//# sourceMappingURL=index.js.map
