import React, { useRef } from 'react';
import i18n from 'ui-i18n';
import { pipe, pluck } from 'ramda';
import classnames from 'classnames';
import Typography from '@mui/material/Typography';
import { getAllUsersForTenant, utils } from '@reltio/mdm-sdk';
import { useMdmServicesPath, useMdmTenant } from '../contexts/MdmModuleContext';
import { ReactSelectDropdownIndicatorWithIconButton } from '../ReactSelectDropdownIndicatorWithIconButton';
import { ReactSelectMenuWithPopper } from '../ReactSelectMenuWithPopper';
import { MultiSelect } from '../MultiSelect';
import { customStyles, useStyles } from './styles';
export var UserSelector = function (_a) {
    var selectedUsers = _a.selectedUsers, onChange = _a.onChange, className = _a.className, disableUnderline = _a.disableUnderline;
    var styles = useStyles();
    var inputRef = useRef(null);
    var tenant = useMdmTenant();
    var servicesPath = useMdmServicesPath();
    var valueToOption = function (value) { return ({ value: value, label: value }); };
    var prepareValues = function (values) { return values.map(valueToOption); };
    var filterUsers = function (inputValue) { return function (users) {
        return inputValue ? users.filter(function (username) { return utils.strings.search(username, inputValue); }) : users;
    }; };
    var cachedRequest = useRef(null);
    var getOptions = function (inputValue) {
        if (!cachedRequest.current) {
            cachedRequest.current = getAllUsersForTenant({ tenant: tenant, servicesPath: servicesPath });
        }
        return cachedRequest.current.then(pipe(pluck('username'), filterUsers(inputValue), prepareValues));
    };
    return (React.createElement("div", { className: classnames(styles.root, className), "data-reltio-id": "user-selector" },
        React.createElement(Typography, { className: styles.title, variant: 'subtitle1' }, i18n.text('User')),
        React.createElement(MultiSelect, { value: prepareValues(selectedUsers), onChange: pipe(pluck('value'), onChange), defaultOptions: true, getOptions: getOptions, TextFieldProps: {
                InputProps: { disableUnderline: disableUnderline },
                className: styles.dropDownInput,
                ref: inputRef
            }, components: {
                DropdownIndicator: ReactSelectDropdownIndicatorWithIconButton,
                Menu: ReactSelectMenuWithPopper
            }, styles: customStyles, classes: styles, menuPortalTarget: document.body, menuShouldBlockScroll: true, captureMenuScroll: false, inputRef: inputRef })));
};
