import React, { useCallback, useMemo, useRef, useState } from 'react';
import i18n from 'ui-i18n';
import { AttributeSelectorPopup } from './components/AttributeSelectorPopup';
import { SearchInput } from '../SearchInput';
import { filterItemsInGroups } from './helpers';
import styles from './FacetsSelector.module.css';
export var FacetsSelector = function (_a) {
    var open = _a.open, data = _a.data, selectedFacetsFieldNames = _a.selectedFacetsFieldNames, onOpen = _a.onOpen, onClose = _a.onClose, onFacetToggle = _a.onFacetToggle;
    var _b = useState(''), filterText = _b[0], setFilterText = _b[1];
    var _c = useState(null), lastFacetClicked = _c[0], setLastFacetClicked = _c[1];
    var searchInputRootRef = useRef(null);
    var filteredList = useMemo(function () { return (filterText ? filterItemsInGroups(data, filterText) : data); }, [data, filterText]);
    var showSearchInput = function () { return searchInputRootRef.current.scrollIntoView(true); };
    var handleClose = useCallback(function () {
        onClose();
        setFilterText('');
        setLastFacetClicked(null);
    }, [onClose]);
    var handleListItemClick = useCallback(function (facetConfig, checked, groupId) {
        setLastFacetClicked({ facetConfig: facetConfig, groupId: groupId });
        onFacetToggle(facetConfig, checked);
    }, [onFacetToggle]);
    var handleOpen = useCallback(function () {
        showSearchInput();
        onOpen();
    }, [onOpen]);
    return (React.createElement(React.Fragment, null,
        React.createElement(SearchInput, { classes: { root: styles.inputContainer }, onSearch: setFilterText, onFocus: handleOpen, rootRef: searchInputRootRef, value: filterText, placeholder: i18n.text('Search & add attributes'), height: 40, "data-reltio-id": "reltio-search-more-facets-search-input" }),
        React.createElement(AttributeSelectorPopup, { open: open, selectedFacetsFieldNames: selectedFacetsFieldNames, data: filteredList, lastFacetClicked: lastFacetClicked, anchorRef: searchInputRootRef, onListItemClick: handleListItemClick, onClose: handleClose, onSearch: setFilterText })));
};
export default FacetsSelector;
