"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MetadataTypesSelector = void 0;
var react_1 = __importStar(require("react"));
var classnames_1 = __importDefault(require("classnames"));
var ramda_1 = require("ramda");
var mdm_sdk_1 = require("@reltio/mdm-sdk");
var TextField_1 = __importDefault(require("@mui/material/TextField"));
var ArrowDropDown_1 = __importDefault(require("@mui/icons-material/ArrowDropDown"));
var ListLabel_1 = require("./components/ListLabel");
var SmallIconButton_1 = require("../SmallIconButton");
var SelectionPopup_1 = require("../SelectionPopup");
var useKeyboardNavigation_1 = require("../hooks/useKeyboardNavigation");
var SelectMetadataTypesList_1 = require("./components/SelectMetadataTypesList");
var helpers_1 = require("./helpers");
var styles_1 = require("./styles");
var MIN_CONTAINER_WIDTH = 255;
var LIST_HEIGHT = 245;
var POPUP_HEIGHT = 355;
exports.MetadataTypesSelector = (0, react_1.memo)(function (_a) {
    var _b, _c, _d, _e;
    var placeholder = _a.placeholder, _f = _a.classes, classes = _f === void 0 ? {} : _f, items = _a.items, selectedItemsUris = _a.selectedItemsUris, onChange = _a.onChange, _g = _a.ListLabelProps, ListLabelProps = _g === void 0 ? {} : _g, disabled = _a.disabled, enableEmptyValueUnderline = _a.enableEmptyValueUnderline, single = _a.single, label = _a.label, dataReltioId = _a.dataReltioId, selectionPopupTitle = _a.selectionPopupTitle;
    var styles = (0, styles_1.useStyles)();
    var _h = (0, react_1.useState)(false), isPopupOpen = _h[0], setIsPopupOpen = _h[1];
    var openPopup = (0, react_1.useCallback)(function () { return setIsPopupOpen(true); }, []);
    var closePopup = (0, react_1.useCallback)(function () { return setIsPopupOpen(false); }, []);
    var _j = (0, react_1.useState)(''), filterText = _j[0], setFilterText = _j[1];
    var clearFilterText = (0, react_1.useCallback)(function () { return setFilterText(''); }, []);
    var handleClose = (0, react_1.useCallback)((0, ramda_1.pipe)(clearFilterText, closePopup), [closePopup, clearFilterText]);
    var filteredItems = items
        .filter(function (_a) {
        var label = _a.label;
        return mdm_sdk_1.utils.strings.search(label, filterText);
    })
        .map(function (item, index) { return ({ item: { item: __assign(__assign({}, item), { filterText: filterText }) }, index: index }); });
    var selectedLabels = (0, react_1.useMemo)(function () {
        return (0, ramda_1.pipe)((0, ramda_1.map)(function (uri) { return items.find((0, ramda_1.propEq)('uri', uri)); }), (0, ramda_1.reject)(ramda_1.isNil), helpers_1.getItemLabels)(selectedItemsUris);
    }, [selectedItemsUris, items]);
    var handleListItemClick = (0, react_1.useCallback)(function (item, checked) {
        if (single) {
            onChange(checked ? [item.uri] : []);
            handleClose();
        }
        else {
            onChange(checked
                ? selectedItemsUris.concat(item.uri)
                : selectedItemsUris.filter(function (uri) { return uri !== item.uri; }));
        }
    }, [selectedItemsUris, onChange, single, handleClose]);
    var handleSearchOnEnter = (0, react_1.useCallback)(function (_a) {
        var item = _a.item;
        var checked = !selectedItemsUris.includes(item.uri);
        handleListItemClick(item, checked);
    }, [selectedItemsUris, handleListItemClick]);
    var _k = (0, useKeyboardNavigation_1.useKeyboardNavigation)({
        items: filteredItems,
        open: isPopupOpen,
        onSelectFocusedItem: handleSearchOnEnter,
        selectedItems: selectedItemsUris,
        onClose: handleClose
    }), focusIndex = _k.focusIndex, handleKeyDown = _k.handleKeyDown;
    var rootRef = (0, react_1.useRef)();
    var rootWidth = rootRef.current ? rootRef.current.getBoundingClientRect().width : 0;
    var containerWidth = Math.max(rootWidth, MIN_CONTAINER_WIDTH);
    var noTypesSelected = selectedItemsUris.length === 0;
    return (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement(TextField_1.default, { label: label, ref: rootRef, InputProps: {
                startAdornment: noTypesSelected && !placeholder ? null : (react_1.default.createElement("div", { "data-reltio-id": "metadata-types-selector-start-adornment", className: (0, classnames_1.default)(styles.inputText, classes.inputText) }, noTypesSelected ? (react_1.default.createElement("div", null, placeholder)) : (react_1.default.createElement(ListLabel_1.ListLabel, __assign({}, ListLabelProps, { list: selectedLabels }))))),
                classes: {
                    root: styles.inputRoot,
                    input: (0, classnames_1.default)(styles.input, classes.input, (_b = {},
                        _b[styles.emptyInput] = noTypesSelected && !placeholder,
                        _b)),
                    disabled: (0, classnames_1.default)(styles.disabledInput, (_c = {}, _c[styles.disabledPointer] = disabled, _c)),
                    underline: styles.disabledUnderline
                },
                endAdornment: (react_1.default.createElement(SmallIconButton_1.SmallIconButton, { size: 'L', icon: ArrowDropDown_1.default, iconClassName: (0, classnames_1.default)(styles.icon, (_d = {},
                        _d[styles['popup-opened-icon']] = isPopupOpen,
                        _d)), disabled: disabled })),
                readOnly: true,
                disableUnderline: noTypesSelected && !enableEmptyValueUnderline
            }, inputProps: {
                tabIndex: -1
            }, InputLabelProps: {
                classes: {
                    root: (0, classnames_1.default)(styles.inputLabel, classes.label)
                }
            }, value: "", onClick: disabled ? undefined : openPopup, classes: { root: (0, classnames_1.default)(styles.root, classes.root) }, size: "small", variant: "filled", disabled: disabled, "data-reltio-id": dataReltioId }),
        react_1.default.createElement(SelectionPopup_1.SelectionPopup, { open: isPopupOpen, anchorEl: rootRef.current, onClose: handleClose, onSearch: setFilterText, title: selectionPopupTitle, containerWidth: containerWidth, containerHeight: POPUP_HEIGHT, searchInputOnKeyDown: handleKeyDown, transformOrigin: { horizontal: 'left', vertical: 'top' }, anchorOrigin: { horizontal: 'left', vertical: 'bottom' }, PaperProps: (_e = {}, _e['data-reltio-id'] = "".concat(dataReltioId, "-popup"), _e) },
            react_1.default.createElement(SelectMetadataTypesList_1.SelectMetadataTypesList, { items: filteredItems, onItemClick: handleListItemClick, selectedItems: selectedItemsUris, width: containerWidth, height: LIST_HEIGHT, focusIndex: focusIndex }))));
});
exports.MetadataTypesSelector.displayName = 'MetadataTypesSelector';
