import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { json } from "@codemirror/lang-json";
import { CodeMirrorEditor } from "../codemirror";
import { Button, VModal, VModalBody, VModalFooter, VModalTitle, useToast } from "@vertesia/ui/core";
import { basicSetup } from "codemirror";
import { useMemo, useRef } from "react";
import { JSONCode } from '../json-view';
function contentToJSON(content) {
    if (!content)
        return undefined;
    content = content.trim();
    if (!content)
        return undefined;
    return JSON.parse(content);
}
function jsonToContent(json) {
    if (!json)
        return '';
    return JSON.stringify(json, null, 2);
}
const extensions = [basicSetup, json()];
export function JSONSchemaEditorModal({ schema, isOpen, onClose, readonly = false }) {
    const editorRef = useRef(undefined);
    const toast = useToast();
    const value = useMemo(() => {
        return jsonToContent(schema.schema);
    }, [schema]);
    const onSaveChanges = () => {
        if (editorRef.current) {
            const value = editorRef.current.getValue();
            try {
                const newSchema = contentToJSON(value);
                schema.replaceSchema(newSchema);
                onClose();
            }
            catch (err) {
                toast({
                    status: 'error',
                    title: 'Invalid JSON Schema',
                    description: err.message,
                    duration: 5000
                });
            }
        }
    };
    return (_jsxs(VModal, { onClose: onClose, isOpen: !!isOpen, className: 'min-w-[60vw]', children: [_jsx(VModalTitle, { children: "JSON Schema Editor" }), _jsx(VModalBody, { children: !readonly ? _jsx(CodeMirrorEditor, { value: value, extensions: extensions, editorRef: editorRef })
                    : _jsx(JSONCode, { data: schema.schema || {} }) }), _jsx(VModalFooter, { children: !readonly ? _jsx(Button, { onClick: onSaveChanges, children: "Save changes" }) : null })] }));
}
//# sourceMappingURL=JSONSchemaEditorModal.js.map