import { useEffect, useState, } from 'react';
import { useFirstMountState } from '../../useFirstMountState';
import { useForwardedRef } from '../../useForwardedRef';
export const useLogic = ({ onChange: propsOnChange, defaultValue, value, inputRef: externalInputRef, disabled, onBlur: propsOnBlur, fullWidth, isLoading, placeholder = 'Поиск', inputComponent, hideHelperText = true, ...restProps }) => {
    const inputRef = useForwardedRef(externalInputRef);
    const [internalValue, setInternalValue] = useState(defaultValue || value || '');
    const isFirstRender = useFirstMountState();
    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,
    };
};
