import { jsx as _jsx } from "@emotion/react/jsx-runtime";
import { useCallback, useState, useEffect, useContext, } from 'react';
import { useTranslation } from 'react-i18next';
import { Modal } from '../../components';
import { EngineContext } from '../../providers';
import { Settings } from '../../../engine/components';
import { EventType } from '../../../events';
import { modals } from './components';
export const SettingsModal = () => {
    const { t } = useTranslation();
    const { world } = useContext(EngineContext);
    const [open, setOpen] = useState(false);
    const [type, setType] = useState();
    const handleEditorOpen = useCallback(() => setOpen(true), []);
    const handleEditorClose = useCallback(() => setOpen(false), []);
    const [settings, setSettings] = useState();
    useEffect(() => {
        const handleSettingsMessage = (modalType) => {
            setType(modalType);
            handleEditorOpen();
        };
        window.electron.onSettings(handleSettingsMessage);
    }, []);
    useEffect(() => {
        const handleSettingsUpdate = () => {
            const mainActor = world.data.mainActor;
            const { data } = mainActor.getComponent(Settings);
            setSettings(Object.assign({}, data));
        };
        handleSettingsUpdate();
        world.addEventListener(EventType.SetSettingsValue, handleSettingsUpdate);
        return () => world.removeEventListener(EventType.SetSettingsValue, handleSettingsUpdate);
    }, []);
    if (type === undefined || settings === undefined) {
        return null;
    }
    const modal = modals[type];
    if (modal === undefined) {
        return null;
    }
    const { component: Component, title } = modal;
    return (_jsx(Modal, { title: t(title), open: open, onCancel: handleEditorClose, width: "300px", children: _jsx(Component, { settings: settings }) }));
};
