import { jsx, jsxs } from "react/jsx-runtime";
import { CodeHighlightNode, CodeNode } from "@lexical/code";
import { $generateHtmlFromNodes, $generateNodesFromDOM } from "@lexical/html";
import { AutoLinkNode, LinkNode } from "@lexical/link";
import { ListItemNode, ListNode } from "@lexical/list";
import { $convertFromMarkdownString, $convertToMarkdownString } from "@lexical/markdown";
import { LexicalComposer } from "@lexical/react/LexicalComposer";
import { ContentEditable } from "@lexical/react/LexicalContentEditable";
import { LexicalErrorBoundary } from "@lexical/react/LexicalErrorBoundary";
import { HistoryPlugin } from "@lexical/react/LexicalHistoryPlugin";
import { LinkPlugin } from "@lexical/react/LexicalLinkPlugin";
import { ListPlugin } from "@lexical/react/LexicalListPlugin";
import { MarkdownShortcutPlugin } from "@lexical/react/LexicalMarkdownShortcutPlugin";
import { OnChangePlugin } from "@lexical/react/LexicalOnChangePlugin";
import { RichTextPlugin } from "@lexical/react/LexicalRichTextPlugin";
import { TablePlugin } from "@lexical/react/LexicalTablePlugin";
import { HeadingNode, QuoteNode } from "@lexical/rich-text";
import { TableCellNode, TableNode, TableRowNode } from "@lexical/table";
import { CircularProgress, FormHelperText } from "@mui/material";
import { FontVariantToken } from "@uipath/apollo-core";
import { $getRoot, $insertNodes } from "lexical";
import { useCallback, useId, useMemo } from "react";
import { useSafeLingui } from "../../../i18n/useSafeLingui.js";
import { ApTypography } from "../ap-typography/index.js";
import "./ApRichTextEditor.css";
import AutoLinkPlugin from "./plugins/AutoLinkPlugin.js";
import CodeHighlightPlugin from "./plugins/CodeHighlightPlugin.js";
import { RTE_TRANSFORMERS } from "./plugins/MarkdownTransformers.js";
import ToolbarPlugin from "./plugins/ToolbarPlugin.js";
const ErrorMessage = ({ id, message })=>/*#__PURE__*/ jsx(ApTypography, {
        id: id,
        variant: FontVariantToken.fontSizeS,
        style: {
            color: 'var(--color-error-text)'
        },
        children: message
    });
const EditorTheme = {
    code: 'editor-code',
    heading: {
        h1: 'editor-heading-h1',
        h2: 'editor-heading-h2',
        h3: 'editor-heading-h3',
        h4: 'editor-heading-h4',
        h5: 'editor-heading-h5'
    },
    image: 'editor-image',
    link: 'editor-link',
    list: {
        listitem: 'editor-listitem',
        nested: {
            listitem: 'editor-nested-listitem'
        },
        ol: 'editor-list-ol',
        ul: 'editor-list-ul'
    },
    ltr: 'ltr',
    paragraph: 'editor-paragraph',
    placeholder: 'editor-placeholder',
    quote: 'editor-quote',
    rtl: 'rtl',
    table: 'editor-table',
    tableCell: 'editor-table-cell',
    tableCellEditing: 'editor-table-cell-editing',
    tableCellHeader: 'editor-table-cell-header',
    tableCellPrimarySelected: 'editor-table-cell-primary-selected',
    tableCellSelected: 'editor-table-cell-selected',
    tableSelected: 'editor-table-selected',
    tableSelection: 'editor-table-selection',
    text: {
        bold: 'editor-text-bold',
        code: 'editor-text-code',
        hashtag: 'editor-text-hashtag',
        italic: 'editor-text-italic',
        overflowed: 'editor-text-overflowed',
        strikethrough: 'editor-text-strikethrough',
        underline: 'editor-text-underline',
        underlineStrikethrough: 'editor-text-underlineStrikethrough'
    }
};
const ApRichTextEditor = (props)=>{
    const { label, required, initialContent, placeholder, disabled, helperText, error, errorMessage, onMarkdownChange, onHtmlChange, loading, maxHeight = '100%', inputFormat = 'markdown', dataTestid } = props;
    const { _ } = useSafeLingui();
    const baseId = useId();
    const labelId = `${baseId}-label`;
    const helperId = `${baseId}-helper`;
    const errorId = `${baseId}-error`;
    const getInitialEditorState = useCallback((editor, format, content)=>{
        if ('markdown' === format) return void $convertFromMarkdownString(content ?? '', RTE_TRANSFORMERS);
        const htmlParser = new DOMParser();
        const dom = htmlParser.parseFromString(content ?? '', 'text/html');
        const nodes = $generateNodesFromDOM(editor, dom);
        editor.update(()=>{
            const root = $getRoot();
            root.clear();
            root.select();
            $insertNodes(nodes);
        });
    }, []);
    const editorConfig = useMemo(()=>({
            namespace: 'apollo-rich-text-editor',
            nodes: [
                HeadingNode,
                ListNode,
                ListItemNode,
                CodeNode,
                CodeHighlightNode,
                AutoLinkNode,
                LinkNode,
                QuoteNode,
                TableNode,
                TableCellNode,
                TableRowNode
            ],
            onError (err) {
                throw err;
            },
            theme: EditorTheme,
            editable: !disabled && !loading,
            editorState: (editor)=>getInitialEditorState(editor, inputFormat, initialContent)
        }), [
        disabled,
        loading,
        getInitialEditorState,
        inputFormat,
        initialContent
    ]);
    const getHelperText = useCallback(()=>{
        if (errorMessage) return /*#__PURE__*/ jsx(ErrorMessage, {
            id: errorId,
            message: errorMessage
        });
        if (error) return /*#__PURE__*/ jsx(ErrorMessage, {
            id: errorId,
            message: helperText ?? ''
        });
        return /*#__PURE__*/ jsx(ApTypography, {
            id: helperId,
            variant: FontVariantToken.fontSizeS,
            children: helperText
        });
    }, [
        error,
        errorMessage,
        helperText,
        errorId,
        helperId
    ]);
    return /*#__PURE__*/ jsxs("div", {
        className: "ap-rich-text-editor",
        children: [
            label && /*#__PURE__*/ jsxs("span", {
                id: labelId,
                className: `editor-label${disabled ? ' disabled' : ''}`,
                children: [
                    label,
                    required && ' *'
                ]
            }),
            loading ? /*#__PURE__*/ jsx(LexicalComposer, {
                initialConfig: editorConfig,
                children: /*#__PURE__*/ jsxs("div", {
                    "aria-labelledby": label ? labelId : void 0,
                    role: "application",
                    className: `editor-container disabled${errorMessage || error ? ' error' : ''} loading`,
                    style: {
                        maxHeight
                    },
                    "aria-disabled": true,
                    "aria-invalid": !!(error || errorMessage),
                    children: [
                        /*#__PURE__*/ jsx(ToolbarPlugin, {
                            disabled: true
                        }),
                        /*#__PURE__*/ jsx(CircularProgress, {
                            "aria-label": _({
                                id: 'rich-text-editor.loading'
                            })
                        })
                    ]
                })
            }, "rte-loading") : /*#__PURE__*/ jsxs(LexicalComposer, {
                initialConfig: editorConfig,
                children: [
                    /*#__PURE__*/ jsxs("div", {
                        "aria-labelledby": label ? labelId : void 0,
                        role: "application",
                        className: `editor-container${disabled ? ' disabled' : ''}${errorMessage || error ? ' error' : ''}`,
                        "aria-disabled": disabled,
                        "aria-invalid": !!(error || errorMessage),
                        style: {
                            maxHeight
                        },
                        "aria-errormessage": errorMessage || error && helperText ? errorId : void 0,
                        "aria-describedby": helperText ? helperId : void 0,
                        children: [
                            /*#__PURE__*/ jsx(OnChangePlugin, {
                                onChange: (editorState, editor)=>{
                                    editorState.read(()=>{
                                        onHtmlChange?.($generateHtmlFromNodes(editor));
                                        onMarkdownChange?.($convertToMarkdownString(RTE_TRANSFORMERS));
                                    });
                                }
                            }),
                            /*#__PURE__*/ jsx(ToolbarPlugin, {
                                disabled: disabled
                            }),
                            /*#__PURE__*/ jsxs("div", {
                                className: `editor-inner${disabled ? ' disabled' : ''}`,
                                children: [
                                    /*#__PURE__*/ jsx(RichTextPlugin, {
                                        contentEditable: /*#__PURE__*/ jsx(ContentEditable, {
                                            ariaLabelledBy: label ? labelId : void 0,
                                            className: "editor-input",
                                            disabled: disabled,
                                            ariaDescribedBy: errorMessage ? errorId : helperText ? helperId : void 0,
                                            "data-testid": dataTestid
                                        }),
                                        placeholder: /*#__PURE__*/ jsx("div", {
                                            className: "editor-placeholder",
                                            children: placeholder
                                        }),
                                        ErrorBoundary: LexicalErrorBoundary
                                    }),
                                    /*#__PURE__*/ jsx(ListPlugin, {}),
                                    /*#__PURE__*/ jsx(LinkPlugin, {}),
                                    /*#__PURE__*/ jsx(AutoLinkPlugin, {}),
                                    /*#__PURE__*/ jsx(CodeHighlightPlugin, {}),
                                    /*#__PURE__*/ jsx(MarkdownShortcutPlugin, {
                                        transformers: RTE_TRANSFORMERS
                                    }),
                                    /*#__PURE__*/ jsx(TablePlugin, {
                                        hasCellMerge: false,
                                        hasCellBackgroundColor: false
                                    })
                                ]
                            }),
                            /*#__PURE__*/ jsx(HistoryPlugin, {})
                        ]
                    }),
                    (helperText || errorMessage) && /*#__PURE__*/ jsx(FormHelperText, {
                        component: "div",
                        children: getHelperText()
                    })
                ]
            }, "rte-editor")
        ]
    });
};
export { ApRichTextEditor };
