"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useLogic = void 0;
const react_1 = require("react");
const useForwardedRef_1 = require("../../../useForwardedRef");
const useLogic = ({ value, disabled, isLoading, inputRef: externalInputRef, onChange, }) => {
    const inputRef = (0, useForwardedRef_1.useForwardedRef)(externalInputRef);
    const prevValue = (0, react_1.useRef)(undefined);
    (0, react_1.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,
    };
};
exports.useLogic = useLogic;
