import React, { memo, useCallback, useMemo, useRef, useState } from 'react';
import i18n from 'ui-i18n';
import classnames from 'classnames';
import { identity, pipe, tap, prop, flatten, pick, map, chain, when, always } from 'ramda';
import { SelectionPopup } from '../SelectionPopup';
import { useKeyboardNavigation } from '../hooks/useKeyboardNavigation';
import { AttributeTitle } from './components/AttributeTitle';
import { SelectAttributesList } from '../SelectAttributesList';
import { flattenGroupedItemsData } from '../VirtualGroupedList';
import { filterSelectedAttributes, getAttributeIndex, getContainerWidth, getOnEnterHandler, prepareGroupsForSelectAttributeList } from './helpers';
import { ATTRIBUTES_LIST_WIDTH, ATTRIBUTES_LIST_HEIGHT, ATTRIBUTES_POPUP_HEIGHT, ATTRIBUTES_LIST_MAX_WIDTH } from './constants';
import { useStyles } from './styles';
var BasicAttributeSelector = function (_a) {
    var className = _a.className, itemsGroups = _a.itemsGroups, value = _a.value, getLabel = _a.getLabel, onSelect = _a.onSelect, _b = _a.onRestoreFocus, onRestoreFocus = _b === void 0 ? identity : _b, _c = _a.onOpenPopup, onOpenPopup = _c === void 0 ? identity : _c, _d = _a.disableRestoreFocus, disableRestoreFocus = _d === void 0 ? false : _d, _e = _a.disableEnforceFocus, disableEnforceFocus = _e === void 0 ? false : _e, _f = _a.single, single = _f === void 0 ? false : _f, _g = _a.ungroup, ungroup = _g === void 0 ? false : _g, _h = _a.disabled, disabled = _h === void 0 ? false : _h, _j = _a.hideCheckBox, hideCheckBox = _j === void 0 ? false : _j, additionalInfo = _a.additionalInfo;
    var styles = useStyles();
    var _k = useState(null), selectAnchor = _k[0], setSelectAnchor = _k[1];
    var openPopup = function (event) {
        onOpenPopup();
        setSelectAnchor(event.currentTarget);
    };
    var closePopup = useCallback(function () { return setSelectAnchor(null); }, []);
    var isPopupOpen = !!selectAnchor;
    var _l = useState(''), filterText = _l[0], setFilterText = _l[1];
    var clearFilterText = useCallback(function () { return setFilterText(''); }, []);
    var _m = useState([]), selectedAttributes = _m[0], setSelectedAttributes = _m[1];
    var clearSelectedAttributes = useCallback(function () { return setSelectedAttributes([]); }, []);
    var filteredItemsGroups = useMemo(function () { return prepareGroupsForSelectAttributeList(filterText, itemsGroups); }, [itemsGroups, filterText]);
    var items = useMemo(function () {
        return pipe(when(always(ungroup), chain(pipe(prop('items'), flatten, map(pick(['item', 'level']))))), flattenGroupedItemsData)(filteredItemsGroups);
    }, [ungroup, filteredItemsGroups]);
    var containerWidth = useMemo(function () {
        return Math.min(Math.max(getContainerWidth(filteredItemsGroups), ATTRIBUTES_LIST_WIDTH), ATTRIBUTES_LIST_MAX_WIDTH);
    }, [filteredItemsGroups]);
    var handleOnClose = pipe(tap(pipe(clearSelectedAttributes, clearFilterText, closePopup)), onRestoreFocus);
    var searchInputRef = useRef();
    var onListItemClick = useCallback(function (attribute, checked) {
        onSelect({
            checked: checked,
            attribute: attribute,
            index: checked ? selectedAttributes.length : getAttributeIndex(selectedAttributes, attribute),
            selectedAttributes: selectedAttributes
        });
        if (single) {
            setSelectedAttributes(checked ? [attribute] : []);
            handleOnClose({});
        }
        else {
            setSelectedAttributes(filterSelectedAttributes({ selectedAttributes: selectedAttributes, attribute: attribute, checked: checked }));
            if (searchInputRef.current) {
                searchInputRef.current.focus();
            }
        }
    }, [selectedAttributes, onSelect, single, handleOnClose, searchInputRef]);
    var handleSearchOnEnter = useCallback(getOnEnterHandler({ onListItemClick: onListItemClick, selectedAttributes: selectedAttributes }), [
        onListItemClick,
        selectedAttributes
    ]);
    var _o = useKeyboardNavigation({
        items: items,
        open: isPopupOpen,
        onSelectFocusedItem: handleSearchOnEnter,
        selectedItems: selectedAttributes,
        onClose: handleOnClose
    }), focusIndex = _o.focusIndex, handleKeyDown = _o.handleKeyDown;
    return (React.createElement("div", { className: classnames(styles.selector, className), "data-reltio-id": "attribute-selector" },
        React.createElement(AttributeTitle, { value: value, getLabel: getLabel, onSelectAttributeClick: openPopup, disabled: disabled }),
        React.createElement(SelectionPopup, { open: isPopupOpen, anchorEl: selectAnchor, onClose: handleOnClose, onSearch: setFilterText, title: i18n.text('Select attribute'), additionalInfo: additionalInfo, containerWidth: containerWidth, containerHeight: ATTRIBUTES_POPUP_HEIGHT, searchInputOnKeyDown: handleKeyDown, anchorOrigin: { horizontal: 'right', vertical: 'bottom' }, searchInputRef: searchInputRef, disableRestoreFocus: disableRestoreFocus, disableEnforceFocus: disableEnforceFocus },
            React.createElement(SelectAttributesList, { items: items, onItemClick: onListItemClick, selectedAttributes: selectedAttributes, width: containerWidth, height: ATTRIBUTES_LIST_HEIGHT, focusIndex: focusIndex, hideCheckBox: hideCheckBox }))));
};
export default memo(BasicAttributeSelector);
