import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useMemo, useState } from 'react';
import { Ellipsis as DotsIcon } from '@gravity-ui/icons';
import { Button, Icon, Loader, Menu, Popup } from '@gravity-ui/uikit';
import { SharedStateKey } from "../../../behavior/SharedState/index.js";
import { useSharedEditingState } from "../../../../react-utils/useSharedEditingState.js";
import { cn } from "../../../../classname.js";
import { TextAreaFixed as TextArea } from "../../../../forms/TextInput.js";
import { i18n } from "../../../../i18n/common/index.js";
import { useBooleanState, useElementState } from "../../../../react-utils/index.js";
import { removeNode } from "../../../../utils/index.js";
import { MermaidConsts } from "../MermaidSpecs/const.js";
export const cnMermaid = cn('Mermaid');
export const STOP_EVENT_CLASSNAME = 'prosemirror-stop-event';
import "./Mermaid.css";
const b = cnMermaid;
const MermaidPreview = ({ mermaidInstance, text = '', }) => {
    const [svg, setSvg] = useState();
    const [error, setError] = useState(null);
    useEffect(() => {
        const p = async () => {
            if (mermaidInstance) {
                try {
                    // Validates syntax and throws error if text is invalid
                    await mermaidInstance.parse(text);
                    const { svg: S } = await mermaidInstance.render(`mermaid-${Date.now()}`, text);
                    setSvg(S);
                    setError(null);
                }
                catch (e) {
                    setError(e.message);
                }
            }
        };
        p();
    }, [mermaidInstance, text]);
    if (error) {
        return _jsx("div", { className: b('Error'), children: error && _jsx("div", { children: error }) });
    }
    return (_jsx("div", { className: b('Preview'), children: svg ? _jsx("div", { className: "mermaid", dangerouslySetInnerHTML: { __html: svg } }) : _jsx(Loader, {}) }));
};
const DiagramEditMode = ({ initialText, onSave, onCancel, mermaidInstance }) => {
    const [text, setText] = useState(initialText || '');
    return (_jsxs("div", { className: b(), children: [_jsx(MermaidPreview, { mermaidInstance: mermaidInstance, text: text }), _jsxs("div", { className: b('Editor'), children: [_jsx("div", { children: _jsx(TextArea, { controlProps: {
                                className: STOP_EVENT_CLASSNAME,
                            }, value: text, onUpdate: (v) => {
                                setText(v);
                            }, autoFocus: true }) }), _jsx("div", { className: b('Controls'), children: _jsxs("div", { children: [_jsx(Button, { onClick: onCancel, view: 'flat', children: _jsx("span", { className: STOP_EVENT_CLASSNAME, children: i18n('cancel') }) }), _jsx(Button, { onClick: () => onSave(text), view: 'action', children: _jsx("span", { className: STOP_EVENT_CLASSNAME, children: i18n('save') }) })] }) })] })] }));
};
export const MermaidView = ({ onChange, node, getPos, view, getMermaidInstance }) => {
    const enitityId = node.attrs[MermaidConsts.NodeAttrs.EntityId];
    const entityKey = useMemo(() => SharedStateKey.define({ name: enitityId }), [enitityId]);
    const [editing, setEditing, unsetEditing] = useSharedEditingState(view, entityKey);
    const [menuOpen, , closeMenu, toggleMenuOpen] = useBooleanState(false);
    const [anchorElement, setAnchorElement] = useElementState();
    const [mermaidInstance, setMermaidInstance] = useState(null);
    useEffect(() => {
        const waitForMermaid = () => setTimeout(() => {
            const instance = getMermaidInstance();
            if (instance) {
                setMermaidInstance(instance);
                return;
            }
            waitForMermaid();
        }, 100);
        waitForMermaid();
    }, []);
    if (editing) {
        return (_jsx(DiagramEditMode, { initialText: node.attrs[MermaidConsts.NodeAttrs.content], mermaidInstance: mermaidInstance, onCancel: unsetEditing, onSave: (v) => {
                onChange({ [MermaidConsts.NodeAttrs.content]: v });
                unsetEditing();
            } }));
    }
    return (_jsxs("div", { className: b(), onDoubleClick: setEditing, children: [_jsx(MermaidPreview, { mermaidInstance: mermaidInstance, text: node.attrs[MermaidConsts.NodeAttrs.content] }), _jsxs("div", { children: [_jsx(Button, { onClick: toggleMenuOpen, ref: setAnchorElement, size: 's', className: STOP_EVENT_CLASSNAME, children: _jsx(Icon, { data: DotsIcon, className: STOP_EVENT_CLASSNAME }) }), _jsx(Popup, { open: menuOpen, anchorElement: anchorElement, onOpenChange: closeMenu, placement: "bottom-end", children: _jsxs(Menu, { children: [_jsx(Menu.Item, { onClick: () => {
                                        setEditing();
                                        closeMenu();
                                    }, children: i18n('edit') }), _jsx(Menu.Item, { onClick: () => {
                                        const pos = getPos();
                                        if (pos === undefined)
                                            return;
                                        removeNode({
                                            node,
                                            pos,
                                            tr: view.state.tr,
                                            dispatch: view.dispatch,
                                        });
                                    }, children: i18n('remove') })] }) })] })] }));
};
//# sourceMappingURL=MermaidView.js.map
