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);
};
import React, { useRef, useState, useCallback, useMemo, memo } from 'react';
import classnames from 'classnames';
import { isNil, map, pipe, propEq, reject } from 'ramda';
import { utils } from '@reltio/mdm-sdk';
import TextField from '@mui/material/TextField';
import ArrowDropDown from '@mui/icons-material/ArrowDropDown';
import { ListLabel } from './components/ListLabel';
import { SmallIconButton } from '../SmallIconButton';
import { SelectionPopup } from '../SelectionPopup';
import { useKeyboardNavigation } from '../hooks/useKeyboardNavigation';
import { SelectMetadataTypesList } from './components/SelectMetadataTypesList';
import { getItemLabels } from './helpers';
import { useStyles } from './styles';
var MIN_CONTAINER_WIDTH = 255;
var LIST_HEIGHT = 245;
var POPUP_HEIGHT = 355;
export var MetadataTypesSelector = 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 = useStyles();
    var _h = useState(false), isPopupOpen = _h[0], setIsPopupOpen = _h[1];
    var openPopup = useCallback(function () { return setIsPopupOpen(true); }, []);
    var closePopup = useCallback(function () { return setIsPopupOpen(false); }, []);
    var _j = useState(''), filterText = _j[0], setFilterText = _j[1];
    var clearFilterText = useCallback(function () { return setFilterText(''); }, []);
    var handleClose = useCallback(pipe(clearFilterText, closePopup), [closePopup, clearFilterText]);
    var filteredItems = items
        .filter(function (_a) {
        var label = _a.label;
        return utils.strings.search(label, filterText);
    })
        .map(function (item, index) { return ({ item: { item: __assign(__assign({}, item), { filterText: filterText }) }, index: index }); });
    var selectedLabels = useMemo(function () {
        return pipe(map(function (uri) { return items.find(propEq('uri', uri)); }), reject(isNil), getItemLabels)(selectedItemsUris);
    }, [selectedItemsUris, items]);
    var handleListItemClick = 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 = useCallback(function (_a) {
        var item = _a.item;
        var checked = !selectedItemsUris.includes(item.uri);
        handleListItemClick(item, checked);
    }, [selectedItemsUris, handleListItemClick]);
    var _k = useKeyboardNavigation({
        items: filteredItems,
        open: isPopupOpen,
        onSelectFocusedItem: handleSearchOnEnter,
        selectedItems: selectedItemsUris,
        onClose: handleClose
    }), focusIndex = _k.focusIndex, handleKeyDown = _k.handleKeyDown;
    var rootRef = 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.createElement(React.Fragment, null,
        React.createElement(TextField, { label: label, ref: rootRef, InputProps: {
                startAdornment: noTypesSelected && !placeholder ? null : (React.createElement("div", { "data-reltio-id": "metadata-types-selector-start-adornment", className: classnames(styles.inputText, classes.inputText) }, noTypesSelected ? (React.createElement("div", null, placeholder)) : (React.createElement(ListLabel, __assign({}, ListLabelProps, { list: selectedLabels }))))),
                classes: {
                    root: styles.inputRoot,
                    input: classnames(styles.input, classes.input, (_b = {},
                        _b[styles.emptyInput] = noTypesSelected && !placeholder,
                        _b)),
                    disabled: classnames(styles.disabledInput, (_c = {}, _c[styles.disabledPointer] = disabled, _c)),
                    underline: styles.disabledUnderline
                },
                endAdornment: (React.createElement(SmallIconButton, { size: 'L', icon: ArrowDropDown, iconClassName: classnames(styles.icon, (_d = {},
                        _d[styles['popup-opened-icon']] = isPopupOpen,
                        _d)), disabled: disabled })),
                readOnly: true,
                disableUnderline: noTypesSelected && !enableEmptyValueUnderline
            }, inputProps: {
                tabIndex: -1
            }, InputLabelProps: {
                classes: {
                    root: classnames(styles.inputLabel, classes.label)
                }
            }, value: "", onClick: disabled ? undefined : openPopup, classes: { root: classnames(styles.root, classes.root) }, size: "small", variant: "filled", disabled: disabled, "data-reltio-id": dataReltioId }),
        React.createElement(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.createElement(SelectMetadataTypesList, { items: filteredItems, onItemClick: handleListItemClick, selectedItems: selectedItemsUris, width: containerWidth, height: LIST_HEIGHT, focusIndex: focusIndex }))));
});
MetadataTypesSelector.displayName = 'MetadataTypesSelector';
