import { __assign, __read, __rest } from "tslib";
import './TextField.css';
import React, { forwardRef, useState } from 'react';
import TextAreaAutoSize from 'react-textarea-autosize';
import { useForkRef } from '../../hooks/useForkRef/useForkRef';
import { IconClose } from '../../icons/IconClose/IconClose';
import { IconSelect } from '../../icons/IconSelect/IconSelect';
import { IconSelectOpen } from '../../icons/IconSelectOpen/IconSelectOpen';
import { cn } from '../../utils/bem';
import { getSizeByMap } from '../../utils/getSizeByMap';
import { usePropsHandler } from '../EventInterceptor/usePropsHandler';
import { FieldCaption } from '../FieldCaption/FieldCaption';
import { FieldLabel } from '../FieldLabel/FieldLabel';
import { sizeMap, textFieldPropFormDefault, textFieldPropSizeDefault, textFieldPropViewDefault, textFieldPropWidthDefault, } from './helpers';
export var COMPONENT_NAME = 'TextField';
export var cnTextField = cn(COMPONENT_NAME);
export function TextFieldRender(props, ref) {
    var textFieldRef = React.useRef(null);
    var inputRef = React.useRef(null);
    var _a = usePropsHandler(COMPONENT_NAME, props, textFieldRef), className = _a.className, _b = _a.type, type = _b === void 0 ? 'text' : _b, value = _a.value, onChange = _a.onChange, id = _a.id, name = _a.name, rows = _a.rows, cols = _a.cols, minRows = _a.minRows, maxRows = _a.maxRows, inputRefProp = _a.inputRef, maxLength = _a.maxLength, disabled = _a.disabled, _c = _a.size, size = _c === void 0 ? textFieldPropSizeDefault : _c, _d = _a.view, view = _d === void 0 ? textFieldPropViewDefault : _d, _e = _a.form, form = _e === void 0 ? textFieldPropFormDefault : _e, state = _a.state, status = _a.status, _f = _a.width, width = _f === void 0 ? textFieldPropWidthDefault : _f, onBlur = _a.onBlur, onFocus = _a.onFocus, _g = _a.autoFocus, autoFocus = _g === void 0 ? false : _g, placeholder = _a.placeholder, leftSide = _a.leftSide, rightSide = _a.rightSide, autoComplete = _a.autoComplete, withClearButton = _a.withClearButton, max = _a.max, min = _a.min, readOnly = _a.readOnly, required = _a.required, _h = _a.step, step = _h === void 0 ? 1 : _h, tabIndex = _a.tabIndex, ariaLabel = _a.ariaLabel, label = _a.label, _j = _a.labelPosition, labelPosition = _j === void 0 ? 'top' : _j, caption = _a.caption, iconSizeProp = _a.iconSize, focused = _a.focused, component = _a.component, otherProps = __rest(_a, ["className", "type", "value", "onChange", "id", "name", "rows", "cols", "minRows", "maxRows", "inputRef", "maxLength", "disabled", "size", "view", "form", "state", "status", "width", "onBlur", "onFocus", "autoFocus", "placeholder", "leftSide", "rightSide", "autoComplete", "withClearButton", "max", "min", "readOnly", "required", "step", "tabIndex", "ariaLabel", "label", "labelPosition", "caption", "iconSize", "focused", "component"]);
    var _k = __read(useState(autoFocus), 2), focus = _k[0], setFocus = _k[1];
    var textarea = type === 'textarea';
    var LeftIcon = leftSide;
    var RightIcon = rightSide;
    var leftSideIsString = typeof leftSide === 'string';
    var rightSideIsString = typeof rightSide === 'string';
    var iconSize = getSizeByMap(sizeMap, size, iconSizeProp);
    var handleChange = function (e) {
        var value = e.target.value;
        !disabled && (onChange === null || onChange === void 0 ? void 0 : onChange({ e: e, id: id, name: name, value: value || null }));
    };
    var handleBlur = function (e) {
        setFocus(false);
        onBlur === null || onBlur === void 0 ? void 0 : onBlur(e);
    };
    var handleFocus = function (e) {
        setFocus(true);
        onFocus === null || onFocus === void 0 ? void 0 : onFocus(e);
    };
    var commonProps = {
        'className': cnTextField('Input'),
        'value': value || '',
        'onChange': handleChange,
        // onChange: onChange,
        maxLength: maxLength,
        disabled: disabled,
        'onBlur': handleBlur,
        'onFocus': handleFocus,
        autoFocus: autoFocus,
        placeholder: placeholder,
        autoComplete: autoComplete,
        readOnly: readOnly,
        // required,
        tabIndex: tabIndex,
        name: name,
        'id': id ? id.toString() : '',
        'aria-label': ariaLabel
    };
    var textareaProps = {
        rows: rows,
        cols: cols,
        minRows: minRows || rows,
        maxRows: maxRows || rows,
        inputRef: useForkRef([inputRef, inputRefProp])
    };
    var inputProps = {
        type: type,
        max: max,
        min: min,
        step: step,
        ref: useForkRef([inputRef, inputRefProp])
    };
    var handleClear = function (e) {
        var _a;
        onChange === null || onChange === void 0 ? void 0 : onChange({
            e: e,
            value: ''
        });
        (_a = inputRef.current) === null || _a === void 0 ? void 0 : _a.focus();
    };
    var changeNumberValue = function (e, isIncrement) {
        var _a;
        if (isIncrement === void 0) { isIncrement = true; }
        var currentValue = value || 0;
        currentValue = isIncrement
            ? Number(currentValue) + Number(step)
            : Number(currentValue) - Number(step);
        onChange === null || onChange === void 0 ? void 0 : onChange({
            e: e,
            value: currentValue.toFixed(Number(
            /* Необходимо для того чтобы избежать ситуации, когда по нажатию
            на кнопку прибавляется число с погрешностью.
            Здесь мы берем разрядность дробной части шага и ограничиваем
            результирующее число этой разрядностью */
            (_a = Number(step)
                .toString()
                .split('.')[1]) === null || _a === void 0 ? void 0 : _a.length) || 0)
        });
    };
    return (React.createElement("div", __assign({ className: cnTextField({ labelPosition: labelPosition, size: size, view: view, width: width }, [className]) }, otherProps),
        label && (React.createElement(FieldLabel, { required: required, className: cnTextField('Label', { labelPosition: labelPosition }), size: getSizeByMap(sizeMap, size) }, label)),
        React.createElement("div", { className: cnTextField('Body') },
            React.createElement("div", { className: cnTextField('InputContainer', {
                    view: view,
                    form: form,
                    status: status || state,
                    disabled: disabled,
                    type: type,
                    focus: focus || focused,
                    withValue: !!value
                }), ref: useForkRef([ref, textFieldRef]) },
                LeftIcon && (React.createElement("div", { className: cnTextField('Side', {
                        position: 'left',
                        type: leftSideIsString ? 'string' : 'icon'
                    }), title: typeof leftSide === 'string' ? leftSide : undefined }, leftSideIsString ? (leftSide) : (React.createElement(LeftIcon, { className: cnTextField('Icon'), size: iconSize })))),
                textarea ? (React.createElement(TextAreaAutoSize, __assign({}, commonProps, textareaProps))) : (React.createElement("input", __assign({}, commonProps, inputProps))),
                type === 'number' && (React.createElement("div", { className: cnTextField('Counter') },
                    React.createElement("button", { onClick: function (e) { return changeNumberValue(e, true); }, type: "button", className: cnTextField('CounterButton') },
                        React.createElement(IconSelectOpen, { size: "xs" })),
                    React.createElement("button", { onClick: function (e) { return changeNumberValue(e, false); }, type: "button", className: cnTextField('CounterButton') },
                        React.createElement(IconSelect, { size: "xs" })))),
                value && withClearButton && type !== 'number' && (React.createElement("button", { type: "button", disabled: disabled, onClick: handleClear, className: cnTextField('ClearButton') },
                    React.createElement(IconClose, { size: "xs", className: cnTextField('ClearButtonIcon') }))),
                RightIcon && type !== 'number' && (React.createElement("div", { className: cnTextField('Side', {
                        position: 'right',
                        type: rightSideIsString ? 'string' : 'icon'
                    }), title: typeof rightSide === 'string' ? rightSide : undefined }, rightSideIsString ? (rightSide) : (React.createElement(RightIcon, { className: cnTextField('Icon'), size: iconSize }))))),
            caption && (React.createElement(FieldCaption, { className: cnTextField('Caption'), status: status || state }, caption)))));
}
export var TextField = forwardRef(TextFieldRender);
export * from './helpers';
