import { jsx as _jsx } from "@emotion/react/jsx-runtime";
import { useCallback, useMemo, } from 'react';
import { useTranslation } from 'react-i18next';
import { useCommander } from '../../../../hooks';
import { addValue } from '../../../../commands';
import { formatWidgetName } from '../../../../../utils/format-widget-name';
import { EntityMultiselect } from '../entity-picker';
import { EntityPickerCSS } from './entity-list.style';
import { CONFIG_KEY_MAP, PATH_FIELD_MAP } from './consts';
export const EntityPicker = ({ path, entities, addedEntities, placeholder, type, onCreate, }) => {
    const { t } = useTranslation();
    const { dispatch } = useCommander();
    const rootPath = useMemo(() => path.concat(PATH_FIELD_MAP[type]), [path, type]);
    const options = useMemo(() => entities
        .filter((entity) => !addedEntities.has(entity.name))
        .map((entity) => ({
        label: entity.schema.title
            ? t(entity.schema.title, { ns: entity.namespace })
            : formatWidgetName(entity.name),
        value: entity.name,
    })), [entities, addedEntities]);
    const schemasMap = useMemo(() => entities.reduce((acc, entity) => {
        acc[entity.name] = entity.schema;
        return acc;
    }, {}), [entities]);
    const handleAdd = useCallback((value) => {
        var _a, _b, _c;
        dispatch(addValue(rootPath, {
            name: value,
            [CONFIG_KEY_MAP[type]]: (_c = (_b = (_a = schemasMap[value]).getInitialState) === null || _b === void 0 ? void 0 : _b.call(_a)) !== null && _c !== void 0 ? _c : {},
        }));
    }, [schemasMap, rootPath, type]);
    return (_jsx(EntityMultiselect, { css: EntityPickerCSS, options: options, onAdd: handleAdd, onCreate: onCreate, placeholder: placeholder, type: type }));
};
