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);
};
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
import React, { useState, useMemo, useCallback } from 'react';
import i18n from 'ui-i18n';
import { isEmpty, prop } from 'ramda';
import { typeAheadSearch, getEntityType, isTempUri, isAvailableEntityType, checkMetadataForCreate } from '@reltio/mdm-sdk';
import { EmptyStub } from '../EmptyStub';
import { DropDownSelector } from '../DropDownSelector';
import { EntityOption } from './components/EntityOption';
import { SingleValue } from './components/SingleValue';
import { ClearIndicator } from './components/ClearIndicator';
import { Group } from './components/Group';
import { EntityCreator } from '../EntityCreator';
import { buildEntityOptions } from './helpers';
import { useStyles } from './styles';
var DEFAULT_MAX_TYPEAHEAD_SEARCH_OPTION = 20;
export var EntitySelector = function (_a) {
    var _b = _a.entity, entity = _b === void 0 ? {} : _b, _c = _a.entityTypesUris, entityTypesUris = _c === void 0 ? [] : _c, mode = _a.mode, _d = _a.max, max = _d === void 0 ? DEFAULT_MAX_TYPEAHEAD_SEARCH_OPTION : _d, onChange = _a.onChange, onCreate = _a.onCreate, metadata = _a.metadata, globalSearchRequestOptions = _a.globalSearchRequestOptions, attributeTypesSelectionStrategy = _a.attributeTypesSelectionStrategy, _e = _a.disableLinkClick, disableLinkClick = _e === void 0 ? false : _e, _f = _a.isMasked, isMasked = _f === void 0 ? false : _f, otherProps = __rest(_a, ["entity", "entityTypesUris", "mode", "max", "onChange", "onCreate", "metadata", "globalSearchRequestOptions", "attributeTypesSelectionStrategy", "disableLinkClick", "isMasked"]);
    var styles = useStyles();
    var _g = useState(''), inputValue = _g[0], setInputValue = _g[1];
    var entityTypes = useMemo(function () { return entityTypesUris.map(function (type) { return getEntityType(metadata, type); }).filter(isAvailableEntityType); }, [entityTypesUris, metadata]);
    var creatableEntityTypesUris = useMemo(function () {
        return entityTypesUris.filter(function (entityTypeUri) {
            var entityType = getEntityType(metadata, entityTypeUri);
            return checkMetadataForCreate(mode, entityType);
        });
    }, [entityTypesUris, mode, metadata]);
    var canCreateEntity = useCallback(function (entityTypeUri) {
        if (entityTypes.length === 0) {
            return false;
        }
        return creatableEntityTypesUris.includes(entityTypeUri !== null && entityTypeUri !== void 0 ? entityTypeUri : entityTypes[0].uri);
    }, [creatableEntityTypesUris, entityTypes]);
    var options = useMemo(function () { return (__assign(__assign({}, globalSearchRequestOptions), { max: max, sendMasked: isMasked })); }, [globalSearchRequestOptions, isMasked, max]);
    var handleCreate = onCreate
        ? function (value, entityTypeUri) {
            onCreate(entityTypeUri || entityTypes[0].uri, value);
            setInputValue('');
        }
        : undefined;
    var handleInputChange = function (value) {
        setInputValue(value);
    };
    var handleChange = function (value) {
        if (value !== null) {
            setInputValue('');
            onChange(value);
        }
    };
    var handleClear = function () {
        handleChange({});
    };
    var groupMode = useMemo(function () { return entityTypes.length !== 1; }, [entityTypes]);
    var getOptions = useCallback(function (value) {
        return (isEmpty(entityTypes) ? Promise.resolve([]) : typeAheadSearch(entityTypes, value, options)).then(buildEntityOptions(entityTypes, onCreate));
    }, [entityTypes, onCreate, options]);
    var currentEntityType = (isEmpty(entity) ? entityTypes[0] : getEntityType(metadata, entity.entityType)) || {};
    var createLabel = onCreate &&
        (inputValue
            ? i18n.text('Create "${name}" as new ${entityTypeLabel}', {
                name: inputValue,
                entityTypeLabel: currentEntityType.label
            })
            : i18n.text('Create new ${entityTypeLabel}', { entityTypeLabel: currentEntityType.label }));
    var label = i18n.text('Select ${entityTypeLabel}profile', {
        entityTypeLabel: entityTypes.length === 1 ? "".concat(entityTypes[0].label, " ") : ''
    });
    var isTempEntity = !isEmpty(entity) && isTempUri(entity.entityUri);
    var groupComponent = groupMode ? { Group: Group, GroupHeading: EmptyStub } : {};
    var clearComponent = isTempEntity ? { ClearIndicator: ClearIndicator } : {};
    var TextFieldProps = otherProps.TextFieldProps, dropDownSelectorProps = __rest(otherProps, ["TextFieldProps"]);
    var textFieldProps = useMemo(function () {
        var _a;
        return (__assign(__assign({}, (TextFieldProps || {})), (_a = {}, _a['data-reltio-id'] = 'reltio-entity-selector', _a)));
    }, [TextFieldProps]);
    return (React.createElement(React.Fragment, null,
        React.createElement(DropDownSelector, __assign({ value: !isEmpty(entity) ? entity : undefined, inputValue: inputValue, onInputChange: handleInputChange, getOptions: getOptions, getOptionLabel: prop('entityLabel'), onChange: handleChange, onCreate: handleCreate, onClear: handleClear, label: label, createLabel: createLabel, canCreateOption: canCreateEntity, components: __assign(__assign({ Option: EntityOption, SingleValue: SingleValue }, groupComponent), clearComponent), currentEntityType: currentEntityType, isClearable: true, disableLinkClick: disableLinkClick, TextFieldProps: textFieldProps }, dropDownSelectorProps)),
        isTempEntity && (React.createElement("div", { "data-reltio-id": "entity-creator", className: styles.creatorWrapper },
            React.createElement(EntityCreator, { mode: mode, attributeTypesSelectionStrategy: attributeTypesSelectionStrategy, entityType: currentEntityType, entityUri: entity.entityUri })))));
};
