"use strict";
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.AttributeSelectorPopup = void 0;
var react_1 = __importStar(require("react"));
var ramda_1 = require("ramda");
var ui_i18n_1 = __importDefault(require("ui-i18n"));
var Typography_1 = __importDefault(require("@mui/material/Typography"));
var mdm_sdk_1 = require("@reltio/mdm-sdk");
var useKeyboardNavigation_1 = require("../../../hooks/useKeyboardNavigation");
var helpers_1 = require("../../helpers");
var VirtualGroupedList_1 = require("../../../VirtualGroupedList");
var FacetsList_1 = require("../FacetsList");
var SelectionPopup_1 = require("../../../SelectionPopup");
var constants_1 = require("../../constants");
var AttributeSelectorPopup_module_css_1 = __importDefault(require("./AttributeSelectorPopup.module.css"));
var defaultLastFacetClicked = {};
var AttributeSelectorPopup = function (_a) {
    var _b, _c;
    var open = _a.open, selectedFacetsFieldNames = _a.selectedFacetsFieldNames, _d = _a.data, data = _d === void 0 ? [] : _d, _e = _a.lastFacetClicked, lastFacetClicked = _e === void 0 ? defaultLastFacetClicked : _e, anchorRef = _a.anchorRef, onListItemClick = _a.onListItemClick, onSearch = _a.onSearch, onClose = _a.onClose;
    var _f = (0, react_1.useState)(constants_1.DEFAULT_LIST_HEIGHT), listHeight = _f[0], setListHeight = _f[1];
    var _g = (0, helpers_1.adjustVerticalPopupLayout)(anchorRef.current, constants_1.DEFAULT_ATTRIBUTE_SELECTOR_POPUP_HEIGHT), verticalOrigin = _g.verticalOrigin, _h = _g.popupHeight, popupHeight = _h === void 0 ? constants_1.DEFAULT_ATTRIBUTE_SELECTOR_POPUP_HEIGHT : _h;
    var maxListHeight = popupHeight - constants_1.POPUP_HEADER_HEIGHT;
    (0, react_1.useEffect)(function () {
        setListHeight(maxListHeight);
    }, [maxListHeight]);
    var handleResizeList = (0, react_1.useCallback)(function (width, height) { return setListHeight((0, ramda_1.clamp)(constants_1.MIN_LIST_HEIGHT, maxListHeight, height)); }, [maxListHeight]);
    var popupActionRef = (0, react_1.useRef)();
    (0, react_1.useEffect)(function () {
        var updatePopupPosition = (0, ramda_1.path)(['current', 'updatePosition'], popupActionRef);
        if (updatePopupPosition)
            updatePopupPosition();
    }, [listHeight]);
    var getFacetGroupData = (0, react_1.useCallback)(function (item, groupId, level) {
        if (level === void 0) { level = 0; }
        return [
            {
                type: 'item',
                item: item,
                moveTo: (0, ramda_1.has)('facetConfig')(lastFacetClicked) &&
                    lastFacetClicked.facetConfig.fieldName === item.fieldName &&
                    groupId === lastFacetClicked.groupId,
                level: level,
                groupId: groupId
            }
        ]
            .concat(item.children
            ? item.children.flatMap(function (subItem) { return getFacetGroupData(subItem, groupId, level + 1); })
            : [])
            .flat()
            .filter(function (item) { return !item.item.hide; });
    }, [lastFacetClicked]);
    var getFacetsData = (0, react_1.useCallback)(function (data) {
        return data
            .map(function (group) { return ({
            type: 'group',
            item: group,
            items: group.facets.filter(function (item) { return !item.hide; }).map(function (item) { return getFacetGroupData(item, group.id); })
        }); })
            .filter(function (group) { return group.items.length; });
    }, [getFacetGroupData]);
    var groupedItems = (0, react_1.useMemo)(function () { return getFacetsData(data); }, [data, getFacetsData]);
    var items = (0, react_1.useMemo)(function () { return (0, VirtualGroupedList_1.flattenGroupedItemsData)(groupedItems); }, [groupedItems]);
    var popupOrigin = (0, helpers_1.constructPopoverOrigin)(verticalOrigin);
    var popupWidth = (_c = (_b = anchorRef.current) === null || _b === void 0 ? void 0 : _b.getBoundingClientRect().width) !== null && _c !== void 0 ? _c : 0;
    var handleSearchOnEnter = (0, react_1.useCallback)(function (_a) {
        var item = _a.item, groupData = _a.groupData;
        onListItemClick(item, !(0, helpers_1.isSelectedFacet)({ facet: item, selectedFacetsFieldNames: selectedFacetsFieldNames }), groupData.groupId);
    }, [onListItemClick, selectedFacetsFieldNames]);
    var _j = (0, useKeyboardNavigation_1.useKeyboardNavigation)({
        items: items,
        open: open,
        onSelectFocusedItem: handleSearchOnEnter,
        selectedItems: selectedFacetsFieldNames
    }), focusIndex = _j.focusIndex, handleKeyDown = _j.handleKeyDown;
    var containerWidth = Math.max(popupWidth || (0, mdm_sdk_1.getMaxItemWidth)('title')(groupedItems), constants_1.DEFAULT_MIN_CONTAINER_WIDTH);
    return (react_1.default.createElement(SelectionPopup_1.SelectionPopup, { open: open, action: popupActionRef, title: ui_i18n_1.default.text('Select attribute'), containerWidth: containerWidth, searchInputOnKeyDown: handleKeyDown, containerHeight: constants_1.POPUP_HEADER_HEIGHT + listHeight, anchorOrigin: popupOrigin, transformOrigin: popupOrigin, headerPlacement: verticalOrigin === 'bottom' ? 'bottom' : 'top', anchorEl: anchorRef.current, disableRestoreFocus: true, onSearch: onSearch, onClose: onClose },
        react_1.default.createElement(FacetsList_1.FacetsList, { focusIndex: focusIndex, selectedFacetsFieldNames: selectedFacetsFieldNames, onListItemClick: onListItemClick, items: items, height: listHeight, onInnerContainerResize: handleResizeList }),
        items.length === 0 && (react_1.default.createElement("div", { className: AttributeSelectorPopup_module_css_1.default.noResultsCaptionContainer },
            react_1.default.createElement(Typography_1.default, { variant: "caption", display: "block", gutterBottom: true }, ui_i18n_1.default.text('No results found'))))));
};
exports.AttributeSelectorPopup = AttributeSelectorPopup;
