import {
  isNumber
} from "./chunk-GWTYSYM2.js";
import {
  padTrimValue
} from "./chunk-7TOYXXZB.js";
import {
  repositionCursor
} from "./chunk-AKU26XW3.js";
import {
  cleanValue
} from "./chunk-LIVX4NT2.js";
import {
  fixedDecimalValue
} from "./chunk-EVBIWR7K.js";
import {
  formatValue
} from "./chunk-VGCIBO3Q.js";
import {
  getLocaleConfig
} from "./chunk-HHOQWXGY.js";
import {
  getSuffix
} from "./chunk-KP23WTR4.js";
import {
  __spreadProps,
  __spreadValues
} from "./chunk-W7FAWX6T.js";

// src/hooks/useNumberInput/useNumberInput.tsx
import { useEffect, useMemo, useState } from "react";
function useNumberInput({
  allowDecimals = true,
  allowNegativeValue = false,
  decimalsLimit,
  maxLength: userMaxLength,
  value: userValue,
  onChange,
  fixedDecimalLength,
  decimalScale,
  prefix,
  suffix,
  intlConfig,
  step,
  min,
  max,
  disableGroupSeparators = false,
  disableAbbreviations = false,
  decimalSeparator: _decimalSeparator,
  groupSeparator: _groupSeparator,
  transformRawValue,
  formatValueOnBlur = true,
  ref
}) {
  if (_decimalSeparator && isNumber(_decimalSeparator)) {
    throw new Error("decimalSeparator cannot be a number");
  }
  if (_groupSeparator && isNumber(_groupSeparator)) {
    throw new Error("groupSeparator cannot be a number");
  }
  const localeConfig = useMemo(() => getLocaleConfig(intlConfig), [intlConfig]);
  const decimalSeparator = _decimalSeparator || localeConfig.decimalSeparator || "";
  const groupSeparator = _groupSeparator || localeConfig.groupSeparator || "";
  if (decimalSeparator && groupSeparator && decimalSeparator === groupSeparator && disableGroupSeparators === false) {
    throw new Error("decimalSeparator cannot be the same as groupSeparator");
  }
  const formatValueOptions = {
    decimalSeparator,
    groupSeparator,
    disableGroupSeparators,
    intlConfig,
    prefix: prefix || localeConfig.prefix,
    suffix
  };
  const cleanValueOptions = {
    decimalSeparator,
    groupSeparator,
    allowDecimals,
    decimalsLimit: decimalsLimit || fixedDecimalLength || 2,
    allowNegativeValue,
    disableAbbreviations,
    prefix: prefix || localeConfig.prefix,
    transformRawValue
  };
  const [stateValue, setStateValue] = useState(
    () => userValue != null ? formatValue(__spreadProps(__spreadValues({}, formatValueOptions), {
      decimalScale,
      value: String(userValue)
    })) : ""
  );
  const [dirty, setDirty] = useState(false);
  const [cursor, setCursor] = useState(0);
  const [changeCount, setChangeCount] = useState(0);
  const [lastKeyStroke, setLastKeyStroke] = useState(null);
  const processChange = (value, selectionStart) => {
    setDirty(true);
    const { modifiedValue, cursorPosition } = repositionCursor({
      selectionStart,
      value,
      lastKeyStroke,
      stateValue,
      groupSeparator
    });
    const stringValue = cleanValue(__spreadValues({
      value: modifiedValue
    }, cleanValueOptions));
    if (userMaxLength && stringValue.replace(/-/g, "").length > userMaxLength) {
      return;
    }
    if (stringValue === "" || stringValue === "-" || stringValue === decimalSeparator) {
      onChange && onChange("", {
        float: null,
        formatted: "",
        value: ""
      });
      setStateValue(stringValue);
      setCursor(1);
      return;
    }
    const stringValueWithoutSeparator = decimalSeparator ? stringValue.replace(decimalSeparator, ".") : stringValue;
    const numberValue = parseFloat(stringValueWithoutSeparator);
    const formattedValue = formatValue(__spreadValues({
      value: stringValue
    }, formatValueOptions));
    if (cursorPosition != null) {
      let newCursor = cursorPosition + (formattedValue.length - value.length);
      newCursor = newCursor <= 0 ? prefix ? prefix.length : 0 : newCursor;
      setCursor(newCursor);
      setChangeCount(changeCount + 1);
    }
    setStateValue(formattedValue);
    if (onChange) {
      const values = {
        float: numberValue,
        formatted: formattedValue,
        value: stringValue
      };
      onChange(stringValue, values);
    }
  };
  const handleOnChange = (event) => {
    const {
      target: { value, selectionStart }
    } = event;
    processChange(value, selectionStart);
  };
  const handleOnFocus = (event) => {
    return stateValue ? stateValue.length : 0;
  };
  const handleOnBlur = (event) => {
    const {
      target: { value }
    } = event;
    const valueOnly = cleanValue(__spreadValues({ value }, cleanValueOptions));
    if (valueOnly === "-" || valueOnly === decimalSeparator || !valueOnly) {
      setStateValue("");
      return;
    }
    const fixedDecimals = fixedDecimalValue(
      valueOnly,
      decimalSeparator,
      fixedDecimalLength
    );
    const newValue = padTrimValue(
      fixedDecimals,
      decimalSeparator,
      decimalScale !== void 0 ? decimalScale : fixedDecimalLength
    );
    const numberValue = parseFloat(newValue.replace(decimalSeparator, "."));
    const formattedValue = formatValue(__spreadProps(__spreadValues({}, formatValueOptions), {
      value: newValue
    }));
    if (onChange && formatValueOnBlur) {
      onChange(newValue, {
        float: numberValue,
        formatted: formattedValue,
        value: newValue
      });
    }
    setStateValue(formattedValue);
  };
  const handleOnKeyDown = (event) => {
    const { key } = event;
    setLastKeyStroke(key);
    if (step && (key === "ArrowUp" || key === "ArrowDown")) {
      event.preventDefault();
      setCursor(stateValue.length);
      const currentValue = parseFloat(
        userValue != null ? String(userValue).replace(decimalSeparator, ".") : cleanValue(__spreadValues({ value: stateValue }, cleanValueOptions))
      ) || 0;
      const newValue = key === "ArrowUp" ? currentValue + step : currentValue - step;
      if (min !== void 0 && newValue < Number(min)) {
        return;
      }
      if (max !== void 0 && newValue > Number(max)) {
        return;
      }
      const fixedLength = String(step).includes(".") ? Number(String(step).split(".")[1].length) : void 0;
      processChange(
        String(fixedLength ? newValue.toFixed(fixedLength) : newValue).replace(
          ".",
          decimalSeparator
        )
      );
    }
  };
  const handleOnKeyUp = (event) => {
    const {
      key,
      currentTarget: { selectionStart }
    } = event;
    if (key !== "ArrowUp" && key !== "ArrowDown" && stateValue !== "-") {
      const suffix2 = getSuffix(stateValue, {
        groupSeparator,
        decimalSeparator
      });
      if (suffix2 && selectionStart && selectionStart > stateValue.length - suffix2.length) {
        if (ref && ref.current) {
          const newCursor = stateValue.length - suffix2.length;
          ref.current.setSelectionRange(newCursor, newCursor);
        }
      }
    }
  };
  useEffect(() => {
    if (userValue == null) {
      setStateValue("");
    }
  }, [userValue]);
  useEffect(() => {
    if (dirty && stateValue !== "-" && ref && ref.current && document.activeElement === ref.current) {
      ref.current.setSelectionRange(cursor, cursor);
    }
  }, [stateValue, cursor, ref, dirty, changeCount]);
  const getRenderValue = () => {
    if (userValue != null && stateValue !== "-" && (!decimalSeparator || stateValue !== decimalSeparator)) {
      return formatValue(__spreadProps(__spreadValues({}, formatValueOptions), {
        decimalScale: dirty ? void 0 : decimalScale,
        value: String(userValue)
      }));
    }
    return stateValue;
  };
  return {
    getRenderValue,
    handleOnChange,
    handleOnBlur,
    handleOnFocus,
    handleOnKeyDown,
    handleOnKeyUp
  };
}

export {
  useNumberInput
};
