import { jsx } from "react/jsx-runtime";
/* empty css            */
import { forwardRef, useEffect, useImperativeHandle } from "react";
import Highlight from "@tiptap/extension-highlight";
import Image from "@tiptap/extension-image";
import Link from "@tiptap/extension-link";
import Mention from "@tiptap/extension-mention";
import { Placeholder } from "@tiptap/extension-placeholder";
import Strike from "@tiptap/extension-strike";
import { useEditor, EditorContent } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import suggestion from "./suggestion.js";
const MentionEditor = forwardRef(
  ({
    value,
    onChange,
    onSend,
    disabled = false,
    maxLength = 5e3,
    placeholder = "Type message...",
    chatId,
    loadParticipantsAvatar,
    ...restConfig
  }, ref) => {
    const editor = useEditor({
      ...restConfig,
      extensions: [
        StarterKit,
        Placeholder.configure({
          placeholder
        }),
        Mention.configure({
          HTMLAttributes: {
            class: "mention"
          },
          suggestion
        }),
        Image.configure({
          inline: true,
          allowBase64: true
        }),
        Link.configure({
          openOnClick: false,
          HTMLAttributes: {
            rel: "noopener noreferrer",
            class: "link"
          }
        }),
        Strike,
        Highlight.configure({
          multicolor: true
          // defaultColor: "#fef3c7",
          // HTMLAttributes: {
          //   class: "highlight",
          //   style:
          //     "background-color: #fef3c7; border-radius: 4px; padding: 2px 4px;",
          // },
        })
      ],
      content: value || "",
      editable: !disabled,
      onUpdate: ({ editor: editor2 }) => {
        const html = editor2.getHTML();
        onChange == null ? void 0 : onChange(html);
      },
      onCreate: ({ editor: editor2 }) => {
        editor2.storage.mentionConfig = {
          chatId,
          loadParticipantsAvatar
        };
      },
      editorProps: {
        handleKeyDown: (view, event) => {
          if (event.key === "Enter" && !event.shiftKey) {
            const { state } = view;
            const { selection } = state;
            const isInList = (editor == null ? void 0 : editor.isActive("bulletList")) || (editor == null ? void 0 : editor.isActive("orderedList"));
            const isMentionActive = state.doc.resolve(selection.from).parent.type.name === "mention" || selection.$from.nodeBefore && selection.$from.nodeBefore.type.name === "mention";
            const textBefore = state.doc.textBetween(
              Math.max(0, selection.from - 20),
              selection.from
            );
            const isTypingMention = /@\w*$/.test(textBefore);
            if (isInList || isMentionActive || isTypingMention) {
              return false;
            }
            event.preventDefault();
            onSend == null ? void 0 : onSend();
            return true;
          }
          return false;
        },
        attributes: {
          class: "prose prose-sm sm:prose lg:prose-lg xl:prose-2xl mx-auto focus:outline-none",
          style: "max-height: 100px; overflow-y: auto; padding: 8px 12px; min-height: 40px;"
        }
      }
    });
    useEffect(() => {
      if (editor && value !== editor.getHTML()) {
        editor.commands.setContent(value || "");
      }
    }, [value, editor]);
    useEffect(() => {
      if (editor) {
        editor.storage.mentionConfig = {
          chatId,
          loadParticipantsAvatar
        };
      }
    }, [editor, chatId, loadParticipantsAvatar]);
    useImperativeHandle(ref, () => ({
      // Text formatting
      toggleBold: () => editor == null ? void 0 : editor.chain().focus().toggleBold().run(),
      toggleItalic: () => editor == null ? void 0 : editor.chain().focus().toggleItalic().run(),
      toggleLink: () => {
        const previousUrl = editor == null ? void 0 : editor.getAttributes("link").href;
        const url = window.prompt("URL", previousUrl);
        if (url === null) return;
        if (url === "") {
          editor == null ? void 0 : editor.chain().focus().extendMarkRange("link").unsetLink().run();
          return;
        }
        editor == null ? void 0 : editor.chain().focus().extendMarkRange("link").setLink({ href: url }).run();
      },
      // File handling
      addImage: (url, alt) => {
        if (url) {
          editor == null ? void 0 : editor.chain().focus().setImage({ src: url, alt: alt || "" }).run();
        }
      },
      // Get content
      getHTML: () => (editor == null ? void 0 : editor.getHTML()) || "",
      getJSON: () => editor == null ? void 0 : editor.getJSON(),
      clearContent: () => editor == null ? void 0 : editor.commands.clearContent(),
      // Editor state
      isEmpty: () => editor ? editor.isEmpty : true,
      // Emoji handling
      insertEmoji: (emoji) => {
        editor == null ? void 0 : editor.chain().focus().insertContent(emoji).run();
      },
      // Additional formatting
      toggleStrike: () => editor == null ? void 0 : editor.chain().focus().toggleStrike().run(),
      toggleHighlight: () => {
        const result = editor == null ? void 0 : editor.chain().focus().toggleHighlight().run();
        return result;
      },
      // List formatting
      toggleBulletList: () => editor == null ? void 0 : editor.chain().focus().toggleBulletList().run(),
      toggleOrderedList: () => editor == null ? void 0 : editor.chain().focus().toggleOrderedList().run(),
      // Heading commands
      toggleH1: () => editor == null ? void 0 : editor.chain().focus().toggleHeading({ level: 1 }).run(),
      toggleH2: () => editor == null ? void 0 : editor.chain().focus().toggleHeading({ level: 2 }).run(),
      toggleH3: () => editor == null ? void 0 : editor.chain().focus().toggleHeading({ level: 3 }).run(),
      toggleH4: () => editor == null ? void 0 : editor.chain().focus().toggleHeading({ level: 4 }).run(),
      toggleH5: () => editor == null ? void 0 : editor.chain().focus().toggleHeading({ level: 5 }).run(),
      toggleH6: () => editor == null ? void 0 : editor.chain().focus().toggleHeading({ level: 6 }).run(),
      // Editor instance
      editor
    }));
    useEffect(() => {
      if (editor) {
        const updateHandler = () => {
          onChange == null ? void 0 : onChange(editor.getHTML());
        };
        editor.on("selectionUpdate", updateHandler);
        return () => {
          editor.off("selectionUpdate", updateHandler);
        };
      }
    }, [editor, onChange]);
    if (!editor) {
      return null;
    }
    return /* @__PURE__ */ jsx("div", { className: "tiptap-editor", children: /* @__PURE__ */ jsx(EditorContent, { editor }) });
  }
);
export {
  MentionEditor
};
