"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useLogic = void 0;
const react_1 = require("react");
const useFirstMountState_1 = require("../../useFirstMountState");
const useForwardedRef_1 = require("../../useForwardedRef");
const useLogic = ({ onChange: propsOnChange, defaultValue, value, inputRef: externalInputRef, disabled, onBlur: propsOnBlur, fullWidth, isLoading, placeholder = 'Поиск', inputComponent, hideHelperText = true, ...restProps }) => {
    const inputRef = (0, useForwardedRef_1.useForwardedRef)(externalInputRef);
    const [internalValue, setInternalValue] = (0, react_1.useState)(defaultValue || value || '');
    const isFirstRender = (0, useFirstMountState_1.useFirstMountState)();
    (0, react_1.useEffect)(() => {
        if (!isFirstRender && value !== internalValue.trim()) {
            setInternalValue(value ? value : '');
        }
        if (!isFirstRender && !value) {
            setInternalValue('');
        }
    }, [value]);
    const onChange = (event) => {
        const trimmedEvent = {
            ...event,
            target: { ...event.target, value: event.target.value.trim() },
        };
        propsOnChange?.(trimmedEvent);
        setInternalValue(event.target.value);
    };
    const onBlur = (event) => {
        propsOnBlur?.(event);
        if (value) {
            setInternalValue(value);
        }
    };
    const createChangeEvent = (eventValue) => {
        return {
            target: {
                value: eventValue,
            },
        };
    };
    const onClearValue = () => {
        onChange?.(createChangeEvent(''));
        inputRef.current.value = '';
        inputRef.current?.focus();
    };
    const isClearButtonDisabled = disabled || (!internalValue && !value);
    return {
        restProps,
        isLoading,
        placeholder,
        inputComponent,
        onChange,
        fullWidth,
        onClearValue,
        inputRef,
        value: internalValue,
        disabled,
        isClearButtonDisabled,
        onBlur,
        hideHelperText,
    };
};
exports.useLogic = useLogic;
