"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "NumberInput", {
    enumerable: true,
    get: function() {
        return NumberInput;
    }
});
const _react = /*#__PURE__*/ _interop_require_wildcard(require("react"));
const _utils = require("../../../../utils");
const _hooks = require("../../../../hooks");
const _constants = require("../../../../utils/constants");
const _utils1 = require("../../utils");
const _NumberInputtokens = require("../../NumberInput.tokens");
const _Inputstyles = require("./Input.styles");
function _getRequireWildcardCache(nodeInterop) {
    if (typeof WeakMap !== "function") return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache = function(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
        return {
            default: obj
        };
    }
    var cache = _getRequireWildcardCache(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {
        __proto__: null
    };
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for(var key in obj){
        if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj.default = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
const NumberInput = /*#__PURE__*/ (0, _react.forwardRef)(({ value, precision, min, max, isLoading, loader, disabled, segmentation, textBefore, textAfter, isManualInput, isInputFocused, setIsInputFocused, setIsAnimationRun, setInnerValue, onChange, onBlur, onKeyDown, onDecrementKey, onIncrementKey, shouldFocusInput, onFocusHandled, ...rest }, ref)=>{
    const [dynamicWidth, setDynamicWidth] = (0, _react.useState)(value ? `${String(value).length}ch` : _utils1.defaultCharacterWidth);
    const [lastValidValue, setLastValidValue] = (0, _react.useState)(value);
    const [errorClass, setErrorClass] = (0, _react.useState)(undefined);
    const [errorValue, setErrorValue] = (0, _react.useState)();
    const inputHelperRef = (0, _react.useRef)(null);
    const wrapperRef = (0, _react.useRef)(null);
    const textWrapperRef = (0, _react.useRef)(null);
    const inputRef = (0, _react.useRef)(null);
    const inputForkRef = (0, _hooks.useForkRef)(inputRef, ref);
    const solidViewClass = segmentation === 'solid' ? _NumberInputtokens.classes.solidView : undefined;
    const manualInputClass = isManualInput ? _NumberInputtokens.classes.manualInput : undefined;
    const getInputWidth = (firstRender = true)=>{
        if (!firstRender && inputHelperRef.current?.clientWidth) {
            return `${inputHelperRef.current?.clientWidth}px`;
        }
        if (value) {
            return `${String(value).length}ch`;
        }
        return _utils1.defaultCharacterWidth;
    };
    const setValues = (event, newValue)=>{
        setLastValidValue(newValue);
        setInnerValue(newValue);
        if (onChange) {
            onChange(event, newValue);
        }
    };
    const validateValue = (newValue)=>{
        if (!newValue?.toString() || !(0, _utils.isNumber)(newValue)) {
            setValues(null, '');
            setIsAnimationRun(false);
            return;
        }
        const resValue = Number(newValue);
        if (max !== undefined && resValue > max) {
            setErrorClass(_NumberInputtokens.classes.errorAnimation);
            setErrorValue(max);
            setIsAnimationRun(true);
            return;
        }
        if (min !== undefined && resValue < min) {
            setErrorClass(_NumberInputtokens.classes.errorAnimation);
            setErrorValue(min);
            setIsAnimationRun(true);
            return;
        }
        if (String(newValue).endsWith('.')) {
            setValues(null, Number(newValue));
            setIsAnimationRun(false);
            return;
        }
        if (precision !== undefined) {
            const preciseNewValue = Number((0, _utils1.getPreciseValue)(newValue, precision));
            setValues(null, preciseNewValue);
        }
        setIsAnimationRun(false);
    };
    const handleManualInputChange = (event)=>{
        if (!isManualInput || disabled) {
            return;
        }
        setIsAnimationRun(true);
        const { value: newValue } = event.target;
        if (!(0, _utils.isNumber)(lastValidValue) && lastValidValue !== '' && !newValue) {
            return;
        }
        if (!newValue) {
            setInnerValue('');
            if (onChange) {
                onChange(event, '');
            }
            return;
        }
        const cleanValue = newValue.replace(_utils1.excludingNumberSchema, '');
        if (cleanValue.endsWith('.') || cleanValue === '-') {
            setInnerValue(cleanValue);
            if (onChange) {
                onChange(event, cleanValue);
            }
            return;
        }
        const isValid = _utils1.numberSchema.test(cleanValue);
        if (!isValid) {
            setValues(event, lastValidValue);
            return;
        }
        if (textWrapperRef?.current && wrapperRef?.current && textWrapperRef?.current?.clientWidth > wrapperRef?.current?.clientWidth) {
            wrapperRef.current.scrollLeft = textWrapperRef.current.offsetWidth - textWrapperRef.current.offsetLeft || 0;
        }
        setValues(event, cleanValue);
    };
    const handleClickInputWrapper = ()=>{
        if (!isManualInput || !inputRef.current) {
            return;
        }
        if (!isInputFocused) {
            inputRef.current.focus();
        }
        setIsInputFocused(true);
    };
    const handleBlur = (event)=>{
        validateValue(value);
        setIsInputFocused(false);
        if (onBlur) {
            onBlur(event);
        }
    };
    const handleFocus = ()=>{
        if (isManualInput && !isInputFocused) {
            inputRef.current?.select();
        }
        setIsInputFocused(true);
    };
    const handleKeyDown = (event)=>{
        if (disabled) {
            return;
        }
        if (event.keyCode === _constants.keyCodes.Up && onIncrementKey) {
            event.preventDefault();
            onIncrementKey();
            return;
        }
        if (event.keyCode === _constants.keyCodes.Down && onDecrementKey) {
            event.preventDefault();
            onDecrementKey();
            return;
        }
        if (event.keyCode === _constants.keyCodes.Enter) {
            event.preventDefault();
            validateValue(value);
            if (onKeyDown) {
                onKeyDown(event);
            }
        }
    };
    const handleEndErrorAnimation = (correctValue)=>{
        setIsAnimationRun(false);
        setIsInputFocused(false);
        setErrorClass(undefined);
        setValues(null, correctValue);
    };
    (0, _react.useEffect)(()=>{
        setDynamicWidth(getInputWidth());
    }, []);
    (0, _hooks.useDidMountEffect)(()=>{
        setDynamicWidth(getInputWidth(false));
    }, [
        value
    ]);
    (0, _react.useEffect)(()=>{
        if (shouldFocusInput && inputRef.current) {
            inputRef.current.focus();
            onFocusHandled?.();
        }
    }, [
        shouldFocusInput
    ]);
    return /*#__PURE__*/ _react.default.createElement(_Inputstyles.InputWrapper, {
        ref: wrapperRef,
        className: (0, _utils.cx)(solidViewClass, errorClass, manualInputClass),
        isManualInput: Boolean(isManualInput),
        onClick: handleClickInputWrapper
    }, /*#__PURE__*/ _react.default.createElement(_Inputstyles.TextWrapper, {
        ref: textWrapperRef
    }, !isLoading && textBefore && /*#__PURE__*/ _react.default.createElement(_Inputstyles.AdditionalText, {
        className: _NumberInputtokens.classes.textBefore
    }, textBefore), isLoading ? /*#__PURE__*/ _react.default.createElement(_Inputstyles.Loader, null, loader || /*#__PURE__*/ _react.default.createElement(_Inputstyles.StyledSpinner, null)) : /*#__PURE__*/ _react.default.createElement(_Inputstyles.DynamicInput, null, /*#__PURE__*/ _react.default.createElement(_Inputstyles.Input, {
        ref: inputForkRef,
        dynamicWidth: dynamicWidth,
        value: value,
        isManualInput: Boolean(isManualInput),
        tabIndex: disabled ? -1 : 0,
        onChange: handleManualInputChange,
        onFocus: handleFocus,
        onBlur: handleBlur,
        onKeyDown: handleKeyDown,
        onAnimationEnd: ()=>handleEndErrorAnimation(Number(errorValue)),
        ...rest
    }), /*#__PURE__*/ _react.default.createElement(_Inputstyles.InputWidthHelper, {
        ref: inputHelperRef
    }, value)), !isLoading && textAfter && /*#__PURE__*/ _react.default.createElement(_Inputstyles.AdditionalText, {
        className: _NumberInputtokens.classes.textAfter
    }, textAfter)));
});
