"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: propsOnChange, onClick: propsOnClick, }) => {
    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.map((item) => item.label).join(', ');
    };
    const preparedValue = prepareValue();
    const hasValue = Boolean(preparedValue);
    const onChange = (newValue) => {
        propsOnChange?.(newValue);
    };
    const onClearAll = (event) => {
        event.stopPropagation();
        onChange?.([]);
        inputRef.current?.focus();
    };
    const onClick = (event) => {
        if (!isLoading) {
            propsOnClick?.(event);
        }
    };
    const isVisibleClearButton = !disabled && !isLoading && Boolean(value?.length);
    return {
        isVisibleClearButton,
        onClearAll,
        onChange,
        onClick,
        isVisibleTagsList: hasValue,
        textFieldProps: {
            value: preparedValue,
            $isHidden: hasValue,
            inputRef,
            onClick,
        },
    };
};
exports.useLogic = useLogic;
