"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useState } from "react";
import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
import { ReactExtension } from "@lexical/react/ReactExtension";
import { useExtensionDependency } from "@lexical/react/useExtensionComponent";
import { $wrapNodeInElement, mergeRegister } from "@lexical/utils";
import { $createParagraphNode, $getNodeByKey, $insertNodes, $isRootOrShadowRoot, COMMAND_PRIORITY_EDITOR, COMMAND_PRIORITY_NORMAL, configExtension, createCommand, declarePeerDependency, defineExtension, safeCast } from "lexical";
import { useToolbarActiveEditor } from "../../plugins/toolbar-plugin/toolbar-active-editor.js";
import { DropDownItem } from "../../ui/dropdown.js";
import { BylineToolbarExtension } from "../byline-toolbar/byline-toolbar-extension.js";
import { InlineImageModal } from "./inline-image-modal.js";
import { $createInlineImageNode, $isInlineImageNode, InlineImageNode } from "./inline-image-node.js";
const OPEN_INLINE_IMAGE_MODAL_COMMAND = createCommand('OPEN_INLINE_IMAGE_MODAL_COMMAND');
const INSERT_INLINE_IMAGE_COMMAND = createCommand('INSERT_INLINE_IMAGE_COMMAND');
const UPDATE_INLINE_IMAGE_COMMAND = createCommand('UPDATE_INLINE_IMAGE_COMMAND');
const CLOSED_STATE = {
    mode: 'insert',
    open: false,
    nodeKey: null,
    initialData: void 0
};
function readNodeAsInitialData(editor, nodeKey) {
    let data;
    editor.getEditorState().read(()=>{
        const node = $getNodeByKey(nodeKey);
        if (!$isInlineImageNode(node)) return;
        data = {
            documentRelation: node.getRelation(),
            src: node.getSrc(),
            altText: node.getAltText(),
            position: node.getPosition(),
            showCaption: node.getShowCaption()
        };
    });
    return data;
}
function InlineImagePlugin() {
    const [editor] = useLexicalComposerContext();
    const { collection } = useExtensionDependency(InlineImageExtension).config;
    const [modalState, setModalState] = useState(CLOSED_STATE);
    useEffect(()=>{
        if (!editor.hasNodes([
            InlineImageNode
        ])) throw new Error('InlineImagePlugin: InlineImageNode not registered on editor');
        return mergeRegister(editor.registerCommand(OPEN_INLINE_IMAGE_MODAL_COMMAND, (payload)=>{
            const nodeKey = payload?.nodeKey;
            if (null != nodeKey) {
                const initialData = readNodeAsInitialData(editor, nodeKey);
                setModalState({
                    mode: 'edit',
                    open: true,
                    nodeKey,
                    initialData
                });
            } else setModalState({
                mode: 'insert',
                open: true,
                nodeKey: null,
                initialData: void 0
            });
            return true;
        }, COMMAND_PRIORITY_NORMAL), editor.registerCommand(INSERT_INLINE_IMAGE_COMMAND, (payload)=>{
            const imageNode = $createInlineImageNode(payload);
            $insertNodes([
                imageNode
            ]);
            if ($isRootOrShadowRoot(imageNode.getParentOrThrow())) $wrapNodeInElement(imageNode, $createParagraphNode).selectEnd();
            return true;
        }, COMMAND_PRIORITY_EDITOR), editor.registerCommand(UPDATE_INLINE_IMAGE_COMMAND, ({ nodeKey, attributes })=>{
            const node = $getNodeByKey(nodeKey);
            if ($isInlineImageNode(node)) {
                node.update(attributes);
                return true;
            }
            return false;
        }, COMMAND_PRIORITY_EDITOR));
    }, [
        editor
    ]);
    const handleSubmit = useCallback((data)=>{
        if (null == data.documentRelation) return;
        const attributes = {
            ...data.documentRelation,
            src: data.src,
            altText: data.altText,
            position: data.position,
            width: data.width,
            height: data.height,
            showCaption: data.showCaption
        };
        if ('edit' === modalState.mode && null != modalState.nodeKey) editor.dispatchCommand(UPDATE_INLINE_IMAGE_COMMAND, {
            nodeKey: modalState.nodeKey,
            attributes
        });
        else editor.dispatchCommand(INSERT_INLINE_IMAGE_COMMAND, attributes);
    }, [
        editor,
        modalState.mode,
        modalState.nodeKey
    ]);
    const handleClose = useCallback(()=>{
        setModalState(CLOSED_STATE);
    }, []);
    return /*#__PURE__*/ jsx(InlineImageModal, {
        isOpen: modalState.open,
        collection: collection,
        data: modalState.initialData,
        onSubmit: handleSubmit,
        onClose: handleClose
    });
}
function InlineImageInsertItem() {
    const editor = useToolbarActiveEditor();
    return /*#__PURE__*/ jsxs(DropDownItem, {
        onClick: ()=>{
            editor.dispatchCommand(OPEN_INLINE_IMAGE_MODAL_COMMAND, null);
        },
        className: "item",
        children: [
            /*#__PURE__*/ jsx("i", {
                className: "icon image"
            }),
            /*#__PURE__*/ jsx("span", {
                className: "text",
                children: "Inline Image"
            })
        ]
    });
}
const InlineImageExtension = defineExtension({
    name: '@byline/richtext-lexical/InlineImage',
    nodes: ()=>[
            InlineImageNode
        ],
    config: safeCast({
        collection: ''
    }),
    dependencies: [
        configExtension(ReactExtension, {
            decorators: [
                /*#__PURE__*/ jsx(InlineImagePlugin, {}, "d")
            ]
        })
    ],
    peerDependencies: [
        declarePeerDependency(BylineToolbarExtension.name, {
            items: [
                {
                    id: '@byline/richtext-lexical/InlineImage/insert',
                    placement: 'insert-menu',
                    order: 40,
                    node: /*#__PURE__*/ jsx(InlineImageInsertItem, {})
                }
            ]
        })
    ]
});
export { INSERT_INLINE_IMAGE_COMMAND, InlineImageExtension, InlineImagePlugin, OPEN_INLINE_IMAGE_MODAL_COMMAND, UPDATE_INLINE_IMAGE_COMMAND };
