import { jsx as _jsx, jsxs as _jsxs } from "@emotion/react/jsx-runtime";
import { useMemo, useCallback, } from 'react';
import { useTranslation } from 'react-i18next';
import { v4 as uuidv4 } from 'uuid';
import { EntityMultiselect } from '../../../components/entity-picker';
import { useConfig, useCommander, useBehaviors, } from '../../../../../hooks';
import { addValue } from '../../../../../commands';
import { BehaviorsStyled, EntityPickerCSS } from './behavior.style';
import { BehaviorPanel } from './behavior-panel';
export const BehaviorsWidget = ({ path }) => {
    const { t } = useTranslation();
    const { dispatch } = useCommander();
    const behaviors = useBehaviors();
    const behaviorsPath = useMemo(() => path.concat('list'), [path]);
    const selectedBehaviors = useConfig(behaviorsPath);
    const availableBehaviors = useMemo(() => {
        const selectedSet = new Set(selectedBehaviors.map((item) => item.name));
        const behaviorNames = Object.keys(behaviors !== null && behaviors !== void 0 ? behaviors : {}).filter((item) => !selectedSet.has(item));
        return behaviorNames.map((key) => ({
            label: key,
            value: key,
        }));
    }, [behaviors, selectedBehaviors]);
    const handleAddBehavior = useCallback((name) => {
        var _a, _b, _c;
        dispatch(addValue(behaviorsPath, {
            id: uuidv4(),
            name,
            options: (_c = (_b = behaviors === null || behaviors === void 0 ? void 0 : (_a = behaviors[name]).getInitialState) === null || _b === void 0 ? void 0 : _b.call(_a)) !== null && _c !== void 0 ? _c : {},
        }));
    }, [dispatch, behaviorsPath, behaviors]);
    const handleCreate = useCallback((name, filepath) => {
        window.electron.createBehavior(name, filepath);
    }, []);
    return (_jsxs(BehaviorsStyled, { children: [_jsx("div", { children: selectedBehaviors.map(({ id, name }) => (_jsx(BehaviorPanel, { id: id, path: behaviorsPath, schema: behaviors === null || behaviors === void 0 ? void 0 : behaviors[name] }, id))) }), _jsx(EntityMultiselect, { css: EntityPickerCSS, size: "small", placeholder: t('components.behaviors.behavior.addNew.title'), options: availableBehaviors, type: "behavior", onAdd: handleAddBehavior, onCreate: handleCreate })] }));
};
