import { useEffect, useRef, } from 'react';
import { useForwardedRef } from '../../../useForwardedRef';
export const useLogic = ({ value, disabled, isLoading, inputRef: externalInputRef, onChange, }) => {
    const inputRef = useForwardedRef(externalInputRef);
    const prevValue = useRef(undefined);
    useEffect(() => {
        if (value && !prevValue.current) {
            prevValue.current = value;
        }
        if (!value && prevValue.current) {
            inputRef.current?.focus();
            prevValue.current = undefined;
        }
    }, [value]);
    const prepareValue = () => {
        if (!value || (Array.isArray(value) && !value.length)) {
            return '';
        }
        return value;
    };
    const preparedValue = prepareValue();
    const hasValue = Boolean(preparedValue);
    const isVisibleClearButton = !disabled && !isLoading && Boolean(value?.length);
    const handleChange = (newValue) => {
        if (!newValue) {
            return onChange?.(undefined);
        }
        onChange?.(newValue.map((item) => item.id));
    };
    const handleClearAll = (event) => {
        event.stopPropagation();
        onChange?.([]);
        inputRef.current?.focus();
    };
    return {
        textFieldProps: {
            $isHidden: hasValue,
            inputRef,
            value: preparedValue,
        },
        isVisibleTagsList: hasValue,
        isVisibleClearButton,
        handleChange,
        handleClearAll,
    };
};
