import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { EditorLoader } from "@powerhousedao/connect/components";
import { useUndoRedoShortcuts } from "@powerhousedao/connect/hooks";
import { toast } from "@powerhousedao/connect/services";
import { RevisionHistory } from "@powerhousedao/design-system/connect";
import { getRevisionFromDate, setRevisionHistoryVisible, showPHModal, useDocumentById, useDocumentModelModuleById, useEditorModuleById, useFallbackEditorModule, useRevisionHistoryVisible, useSelectedTimelineItem, } from "@powerhousedao/reactor-browser";
import { redo, undo } from "document-model/core";
import { Suspense, useEffect, useState } from "react";
import { CenteredErrorMessage, ErrorBoundary, } from "./error-boundary.js";
function EditorError({ message }) {
    return (_jsx("div", { className: "flex size-full items-center justify-center", children: _jsx("h3", { className: "text-lg font-semibold", children: message }) }));
}
export const DocumentEditor = (props) => {
    const { document: initialDocument, onClose, onExport, onOpenSwitchboardLink, } = props;
    const selectedTimelineItem = useSelectedTimelineItem();
    const revisionHistoryVisible = useRevisionHistoryVisible();
    const [document, dispatch] = useDocumentById(initialDocument.header.id);
    const documentId = document?.header.id ?? undefined;
    const documentName = document?.header.name ?? undefined;
    const documentType = document?.header.documentType ?? undefined;
    const preferredEditor = document?.header.meta?.preferredEditor ?? undefined;
    const globalOperations = document?.operations.global ?? [];
    const localOperations = document?.operations.local ?? [];
    const globalRevisionNumber = document?.header.revision.global ?? 0;
    const localRevisionNumber = document?.header.revision.local ?? 0;
    const documentModelModule = useDocumentModelModuleById(documentType);
    const preferredEditorModule = useEditorModuleById(preferredEditor);
    const fallbackEditorModule = useFallbackEditorModule(documentType);
    const editorModule = preferredEditorModule ?? fallbackEditorModule;
    const isLoadingDocument = !document;
    const isLoadingEditor = editorModule &&
        documentType &&
        !editorModule.documentTypes.includes(documentType) &&
        !editorModule.documentTypes.includes("*");
    const canUndo = globalRevisionNumber > 0 || localRevisionNumber > 0;
    const canRedo = !!document?.clipboard.length;
    const addUndoAction = () => dispatch(undo());
    const addRedoAction = () => dispatch(redo());
    useUndoRedoShortcuts({
        undo: addUndoAction,
        redo: addRedoAction,
        canUndo,
        canRedo,
    });
    useEffect(() => {
        return () => {
            window.documentEditorDebugTools?.clear();
        };
    }, []);
    const [editorError, setEditorError] = useState(undefined);
    useEffect(() => {
        if (editorError && editorError.documentId !== documentId) {
            setEditorError(undefined);
        }
    }, [editorError, documentId]);
    const handleEditorError = (error, info) => {
        setEditorError({
            error,
            documentId,
            info,
        });
    };
    if (isLoadingEditor) {
        return _jsx(EditorLoader, { message: "Loading editor" });
    }
    if (isLoadingDocument) {
        return _jsx(EditorLoader, { message: "Loading document" });
    }
    if (!documentModelModule) {
        return (_jsx(EditorError, { message: _jsxs("div", { className: "text-center leading-10", children: [_jsxs("p", { children: ["Unable to open the document because the document model \"", documentType, "\" is not supported."] }), _jsxs("p", { children: ["Go to the", " ", _jsx("button", { type: "button", className: "cursor-pointer underline", onClick: () => {
                                    showPHModal({ type: "settings" });
                                }, children: "package manager" }), " ", "to install this document model"] })] }) }));
    }
    if (!editorModule) {
        return (_jsx(EditorError, { message: _jsxs("div", { className: "text-center leading-10", children: [_jsx("p", { children: "Unable to open the document because no editor has been found" }), _jsxs("p", { children: ["Go to the", " ", _jsx("button", { type: "button", className: "cursor-pointer underline", onClick: () => {
                                    showPHModal({ type: "settings" });
                                }, children: "package manager" }), " ", "an editor for the \"$", documentType, "\" document type"] })] }) }));
    }
    const EditorComponent = editorModule.Component;
    return (_jsx("div", { className: "relative h-full", id: "document-editor-context", "data-editor": editorModule.id, "data-document-type": documentType, children: revisionHistoryVisible ? (_jsx(RevisionHistory, { documentTitle: documentName ?? "", documentId: documentId ?? "", globalOperations: globalOperations, localOperations: localOperations, onClose: () => setRevisionHistoryVisible(false), documentState: document.state, onCopyState: () => {
                toast("Copied document state to clipboard", { type: "success" });
            }, onCopyDocId: () => {
                toast("Copied document ID to clipboard", { type: "success" });
            } }, documentId)) : (_jsx(Suspense, { fallback: _jsx(EditorLoader, { message: "Loading editor" }), name: "EditorLoader", children: _jsx(ErrorBoundary, { fallbackRender: CenteredErrorMessage, resetKeys: [documentId], onError: handleEditorError, loggerContext: ["Connect", "DocumentEditor"], children: !editorError?.error && (_jsx(EditorComponent, { context: {
                        readMode: !!selectedTimelineItem,
                        selectedTimelineRevision: getRevisionFromDate(selectedTimelineItem?.startDate, selectedTimelineItem?.endDate, globalOperations),
                    }, documentId: document.header.id }, documentId)) }) })) }));
};
//# sourceMappingURL=editors.js.map