import { $generateNodesFromDOM } from '@lexical/html';
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
import { $createParagraphNode, $createTextNode, $getRoot } from 'lexical';
import { useEffect } from 'react';

function SetTextPlugin({
  setTextTrigger,
}: {
  setTextTrigger: { value: string; timestamp: number } | null;
}) {
  const [editor] = useLexicalComposerContext();

  useEffect(() => {
    if (setTextTrigger) {
      editor.update(() => {
        const root = $getRoot();
        root.clear();

        const isHTML = /<[a-z][\s\S]*>/i.test(setTextTrigger.value);

        if (isHTML) {
          const parser = new DOMParser();
          const dom = parser.parseFromString(setTextTrigger.value, 'text/html');
          const nodes = $generateNodesFromDOM(editor, dom);
          root.append(...nodes);
        } else {
          const paragraph = $createParagraphNode();
          paragraph.append($createTextNode(setTextTrigger.value));
          root.append(paragraph);
        }

        root.selectStart();
      });
    }
  }, [editor, setTextTrigger]);

  return null;
}

export default SetTextPlugin;
