"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Autocomplete = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const ListItemIcon_1 = __importDefault(require("@mui/material/ListItemIcon"));
const Popper_1 = __importDefault(require("@mui/material/Popper"));
const react_1 = require("react");
const CrossOutlineMd_1 = require("../../icons/CrossOutlineMd");
const DownOutlineMd_1 = require("../../icons/DownOutlineMd");
const Checkbox_1 = require("../Checkbox");
const forwardRefWithGeneric_1 = require("../forwardRefWithGeneric");
const Loader_1 = require("../Loader");
const OverflowTypography_1 = require("../OverflowTypography");
const TagsList_1 = require("../TagsList");
const TextField_1 = require("../TextField");
const classNames_1 = require("../utils/classNames");
const constants_1 = require("./constants");
const styles_1 = require("./styles");
const useLogic_1 = require("./useLogic");
const AutocompleteInner = (props, ref) => {
    const { isValueEmpty, isPopperVisible, autocompleteProps } = (0, useLogic_1.useLogic)(props);
    const inputBaseRef = (0, react_1.useRef)(null);
    const { required, success, error, label, getOptionLabel, helperText, inputRef, multiple, size = 'medium', placeholder = constants_1.DEFAULT_PLACEHOLDER, overflowOption, closeText = 'Закрыть', openText = 'Открыть', clearText = 'Очистить', loadingText = (0, jsx_runtime_1.jsx)(Loader_1.Loader, {}), isLoadedDataError, loadedDataError, noOptionsText, autoHighlight, renderInput: externalRenderInput, renderTags: externalRenderTags, renderOption: externalRenderOption, inputProps, hideHelperText = false, loading, value, onChange, ...restProps } = props;
    const renderInput = (0, react_1.useCallback)((inputParams) => {
        const createStartAdornment = () => {
            if (!multiple || !Array.isArray(value)) {
                return null;
            }
            const tagsListElement = ((0, jsx_runtime_1.jsx)(TagsList_1.TagsList, { data: value, getOptionLabel: (option) => getOptionLabel?.(option) ??
                    option.toString(), inputContainerRef: inputBaseRef, reservedWidth: constants_1.INPUT_MIN_WIDTH, onChange: (tagValues) => {
                    if (!onChange) {
                        return;
                    }
                    const syntheticEvent = {
                        type: 'change',
                        target: { value: tagValues },
                        currentTarget: { value: tagValues },
                    };
                    const reason = 'removeOption';
                    onChange(syntheticEvent, tagValues, reason);
                } }));
            return tagsListElement;
        };
        const generalInputParams = {
            ...inputParams,
            inputProps: {
                ...inputParams.inputProps,
                className: (0, classNames_1.classNames)(inputParams?.inputProps?.className, inputProps?.className),
            },
            InputProps: {
                ...inputParams.InputProps,
                ref: (element) => {
                    inputBaseRef.current = element;
                    const orig = inputParams.InputProps?.ref;
                    if (typeof orig === 'function') {
                        orig(element);
                    }
                    else if (orig) {
                        orig.current = element;
                    }
                },
                // Если есть externalRenderTags, используем renderTags(mui использует inputParams.InputProps?.startAdornment)
                startAdornment: externalRenderTags
                    ? inputParams.InputProps?.startAdornment
                    : createStartAdornment(),
            },
            inputRef,
            required,
            placeholder: isValueEmpty ? placeholder : '',
            label,
            success,
            error,
            helperText,
            size,
            hideHelperText,
        };
        if (externalRenderInput) {
            return externalRenderInput(generalInputParams);
        }
        return (0, jsx_runtime_1.jsx)(TextField_1.TextField, { ...generalInputParams });
    }, [
        isValueEmpty,
        value,
        externalRenderInput,
        externalRenderTags,
        inputRef,
        required,
        placeholder,
        label,
        success,
        error,
        helperText,
        size,
        hideHelperText,
        multiple,
        getOptionLabel,
        onChange,
    ]);
    const renderOption = (0, react_1.useCallback)((optionProps, option, optionState, ownerState) => {
        if (externalRenderOption) {
            return externalRenderOption(optionProps, option, optionState, ownerState);
        }
        const isSelected = Boolean(optionProps['aria-selected']);
        const { key, ...restOptionProps } = optionProps;
        return ((0, jsx_runtime_1.jsxs)(styles_1.StyledMenuItem, { selected: isSelected, ...restOptionProps, children: [multiple && ((0, jsx_runtime_1.jsx)(ListItemIcon_1.default, { children: (0, jsx_runtime_1.jsx)(Checkbox_1.Checkbox, { role: "menuitemcheckbox", checked: isSelected }) })), (0, jsx_runtime_1.jsx)(OverflowTypography_1.OverflowTypography, { rowsCount: constants_1.DEFAULT_AUTOCOMPLETE_ELEMENT_ROWS_COUNT, ...overflowOption, children: optionProps.key })] }, key));
    }, [multiple, overflowOption, externalRenderOption]);
    const renderPopper = (0, react_1.useCallback)((popperProps) => {
        if (!isPopperVisible) {
            return null;
        }
        return (0, jsx_runtime_1.jsx)(Popper_1.default, { ...popperProps });
    }, [isPopperVisible]);
    const renderTags = (0, react_1.useCallback)((tags, getTagProps, ownerState) => {
        if (externalRenderTags) {
            return externalRenderTags(tags, getTagProps, ownerState);
        }
        return null;
    }, [externalRenderTags]);
    return ((0, jsx_runtime_1.jsx)(styles_1.StyledAutocomplete, { ...restProps, ref: ref, size: size, clearText: clearText, closeText: !loading ? closeText : '', openText: !loading ? openText : '', loadingText: loadingText, multiple: multiple, disableCloseOnSelect: multiple, clearIcon: (0, jsx_runtime_1.jsx)(CrossOutlineMd_1.CrossOutlineMd, {}), loading: loading, popupIcon: loading ? (0, jsx_runtime_1.jsx)(Loader_1.Loader, { color: "primary", size: "small" }) : (0, jsx_runtime_1.jsx)(DownOutlineMd_1.DownOutlineMd, {}), forcePopupIcon: true, slotProps: {
            popper: {
                component: renderPopper,
            },
        }, getOptionLabel: getOptionLabel, renderInput: renderInput, renderTags: renderTags, renderOption: renderOption, value: value, onChange: onChange, ...autocompleteProps }));
};
exports.Autocomplete = (0, forwardRefWithGeneric_1.forwardRefWithGeneric)(AutocompleteInner);
