import { __assign, __read, __rest } from "tslib";
import React, { useState, useRef } from "react";
import { useStateProps } from "../hooks/useStateProps";
import InputMask from "../InputMask";
import SelectCountries from "./components/SelectCountries";
import { RightContent } from "./styles";
var REGEX_SPACES = /\s/g;
var MASK = [
    "+",
    "7",
    " ",
    /[1-9]/,
    /\d/,
    /\d/,
    " ",
    /\d/,
    /\d/,
    /\d/,
    " ",
    /\d/,
    /\d/,
    /\d/,
    /\d/
];
var InputPhone = function (_a) {
    var onFocus = _a.onFocus, onBlur = _a.onBlur, value = _a.value, onChange = _a.onChange, _b = _a.testId, testId = _b === void 0 ? "inputPhone" : _b, isDisabled = _a.isDisabled, props = __rest(_a, ["onFocus", "onBlur", "value", "onChange", "testId", "isDisabled"]);
    var _c = __read(useState(props.isAutoFocus), 2), isFocused = _c[0], setFocused = _c[1];
    var _d = __read(useStateProps(value), 2), localValue = _d[0], setLocalValue = _d[1];
    var ref = useRef(null);
    var handleFocus = function (event) {
        setFocused(true);
        if (event.target.value.length === 0) {
            setTimeout(function () {
                var _a;
                ((_a = ref.current) === null || _a === void 0 ? void 0 : _a.inputElement).setSelectionRange(2, 2);
            }, 0);
        }
        onFocus === null || onFocus === void 0 ? void 0 : onFocus(event);
    };
    var handleBlur = function (event, _value) {
        setFocused(false);
        if (_value.replace(REGEX_SPACES, "") === "+7") {
            setLocalValue("");
        }
        onBlur === null || onBlur === void 0 ? void 0 : onBlur(event, _value);
    };
    var handleChange = function (event, _value, id) {
        var val = _value.replace(REGEX_SPACES, " ");
        setLocalValue(val);
        onChange === null || onChange === void 0 ? void 0 : onChange(event, val, id);
    };
    return (React.createElement(InputMask, __assign({ testId: testId }, props, { mask: MASK, isDisabled: isDisabled, iconLeft: isFocused || Boolean(localValue) ? (React.createElement(SelectCountries, { isDisabled: isDisabled })) : undefined, onFocus: handleFocus, onBlur: handleBlur, onChange: handleChange, value: localValue, isShowMaskOnFocus: true, isShowMask: isFocused, placeholderChar: "\u2000", refMask: ref, iconRight: !isFocused && !localValue ? React.createElement(RightContent, null) : undefined })));
};
export default InputPhone;
