import { __assign, __read, __rest } from "tslib";
import React, { useState } from "react";
import NumberFormat from "react-number-format";
import { IconBrokenArrowUp3, IconBrokenArrowDown2 } from "@greenatom/icons";
import { useStateProps } from "../hooks/useStateProps";
import { InputNumberWrapper, StepWrapper, InputNumberStyled } from "./style";
var NOT_NUMBER_REGEXP = /[^\d,.\\]/g;
var InputNumber = function (props) {
    var id = props.id, name = props.name, value = props.value, width = props.width, suffix = props.suffix, thousandSeparator = props.thousandSeparator, maxLength = props.maxLength, isAutoFocus = props.isAutoFocus, decimalScale = props.decimalScale, isFixedDecimalScale = props.isFixedDecimalScale, isNegative = props.isNegative, onValueChange = props.onValueChange, _a = props.type, type = _a === void 0 ? "text" : _a, error = props.error, placeholder = props.placeholder, tooltipContent = props.tooltipContent, _b = props.tooltipPosition, tooltipPosition = _b === void 0 ? "bottom" : _b, title = props.title, _c = props.alignText, alignText = _c === void 0 ? "left" : _c, className = props.className, isDisabled = props.isDisabled, _d = props.isShowClearIcon, isShowClearIcon = _d === void 0 ? true : _d, onFocus = props.onFocus, onBlur = props.onBlur, onChange = props.onChange, onKeyPress = props.onKeyPress, size = props.size, isRequired = props.isRequired, status = props.status, statusText = props.statusText, iconLeft = props.iconLeft, iconRight = props.iconRight, step = props.step, min = props.min, max = props.max, viewType = props.viewType, decimalSeparator = props.decimalSeparator, isReadOnly = props.isReadOnly, _e = props.testId, testId = _e === void 0 ? "inputNumber" : _e, _f = props.readOnlyEmptyText, readOnlyEmptyText = _f === void 0 ? "Не заполнено" : _f, otherProps = __rest(props, ["id", "name", "value", "width", "suffix", "thousandSeparator", "maxLength", "isAutoFocus", "decimalScale", "isFixedDecimalScale", "isNegative", "onValueChange", "type", "error", "placeholder", "tooltipContent", "tooltipPosition", "title", "alignText", "className", "isDisabled", "isShowClearIcon", "onFocus", "onBlur", "onChange", "onKeyPress", "size", "isRequired", "status", "statusText", "iconLeft", "iconRight", "step", "min", "max", "viewType", "decimalSeparator", "isReadOnly", "testId", "readOnlyEmptyText"]);
    var _g = __read(useState(false), 2), isFocused = _g[0], setFocused = _g[1];
    var _h = __read(useStateProps(value), 2), localValue = _h[0], setLocalValue = _h[1];
    var getIsAllowed = function (_value) {
        if (min !== undefined && max !== undefined) {
            return _value >= min && _value <= max;
        }
        else if (min !== undefined) {
            return _value >= min;
        }
        else if (max !== undefined) {
            return _value <= max;
        }
        return true;
    };
    var _j = __read(useStateProps(status), 2), localStatus = _j[0], setLocalStatus = _j[1];
    var handleChange = function (event) {
        var _value = event.target.value;
        var formattedValue = _value
            .replace(NOT_NUMBER_REGEXP, "")
            .replaceAll(",", ".");
        var minus = _value.indexOf("-") === 0 && isNegative ? "-" : "";
        if (getIsAllowed(Number("" + minus + formattedValue)) || _value === "") {
            setLocalStatus(undefined);
        }
        else {
            setLocalStatus("error");
        }
        setLocalValue("" + minus + formattedValue);
        onChange === null || onChange === void 0 ? void 0 : onChange(event, "" + minus + formattedValue, id);
    };
    var handleStep = function (event, x) {
        event.preventDefault();
        event.stopPropagation();
        if (step && !isDisabled) {
            var floatValue = (typeof localValue === "undefined" ? 0 : Number(localValue)) + x * step;
            var localValueLengthDecimal = String(localValue)
                .split(".")
                .splice(0, 1)
                .join().length;
            var stepLengthDecimal = String(step)
                .split("")
                .splice(0, 1)
                .join().length;
            floatValue = Number(floatValue.toFixed(localValueLengthDecimal >= stepLengthDecimal
                ? localValueLengthDecimal
                : stepLengthDecimal));
            if (getIsAllowed(floatValue)) {
                setLocalValue(floatValue);
                onChange === null || onChange === void 0 ? void 0 : onChange(event, typeof value === "number" ? floatValue : String(floatValue), id);
                setLocalValue(floatValue);
                onValueChange === null || onValueChange === void 0 ? void 0 : onValueChange({
                    floatValue: floatValue,
                    formattedValue: String(floatValue),
                    value: String(floatValue)
                });
            }
        }
    };
    var handleFocus = function (event) {
        if (!isReadOnly) {
            onFocus && onFocus(event);
            setFocused(true);
        }
    };
    var handleBlur = function (event) {
        onBlur && onBlur(event, event.target.value);
        setFocused(false);
    };
    var handleKeyPress = function (event) {
        onKeyPress && onKeyPress(event);
    };
    var handleClear = function (event) {
        event.preventDefault();
        event.stopPropagation();
        onValueChange &&
            onValueChange({
                floatValue: undefined,
                formattedValue: "",
                value: ""
            });
        onChange && onChange(event, "", id);
    };
    var baseInputProps = {
        error: error,
        placeholder: placeholder,
        tooltipContent: tooltipContent,
        tooltipPosition: tooltipPosition,
        type: type,
        title: title,
        alignText: alignText,
        className: className,
        width: width,
        isDisabled: isDisabled,
        isShowClearIcon: isShowClearIcon,
        isFocused: isFocused,
        isHasValue: localValue !== undefined && localValue !== null && localValue !== "",
        isPasswordVisible: false,
        onClear: handleClear,
        size: size,
        isRequired: isRequired,
        status: localStatus,
        statusText: statusText,
        iconLeft: iconLeft,
        iconRight: iconRight,
        isShowLabel: true,
        viewType: viewType,
        isReadOnly: isReadOnly,
        testId: testId
    };
    /** В IOS если указать inputMode="decimal", то минуса на клавиатуре не будет.
     * Если необходим минус, приходится показывать полную клавиатуру, через inputMode={undefined}
     */
    return (React.createElement(InputNumberStyled, __assign({ "data-testid": testId }, baseInputProps, { iconRight: step ? (React.createElement(StepWrapper, { isDisabled: isDisabled },
            React.createElement("div", { "data-testid": testId + "_stepper", onClick: function (event) { return handleStep(event, 1); } },
                React.createElement(IconBrokenArrowUp3, { width: 12, height: 12 })),
            React.createElement("div", { "data-testid": testId + "_stepper_toLow", onClick: function (event) { return handleStep(event, -1); } },
                React.createElement(IconBrokenArrowDown2, { width: 12, height: 12 })))) : undefined }, otherProps),
        React.createElement(InputNumberWrapper, null,
            React.createElement(NumberFormat, { "data-testid": testId + "_input", id: id, autoFocus: isAutoFocus, name: name, value: localValue, suffix: suffix, thousandSeparator: thousandSeparator, maxLength: maxLength, decimalScale: decimalScale, fixedDecimalScale: isFixedDecimalScale, decimalSeparator: decimalSeparator, isNumericString: typeof value === "string", onValueChange: onValueChange, allowNegative: isNegative, type: type, inputMode: isNegative ? undefined : "decimal", onFocus: handleFocus, onBlur: handleBlur, onChange: handleChange, onKeyPress: handleKeyPress, disabled: isDisabled, placeholder: isReadOnly && !localValue ? readOnlyEmptyText : "" }))));
};
InputNumber.defaultProps = {
    decimalScale: 0,
    isNegative: true,
    type: "text",
    size: "m",
    alignText: "left",
    tooltipPosition: "bottom"
};
export default InputNumber;
