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

function InitialTextPlugin({ initialText }: { initialText: string | undefined }) {
  const [editor] = useLexicalComposerContext();
  const [hasInitialized, setHasInitialized] = useState(false);

  useEffect(() => {
    if (!hasInitialized && initialText !== undefined) {
      editor.update(() => {
        const root = $getRoot();
        root.clear();

        // Check if it's HTML
        const isHTML = /<[a-z][\s\S]*>/i.test(initialText);

        if (isHTML) {
          const parser = new DOMParser();
          const dom = parser.parseFromString(initialText, 'text/html');
          const nodes = $generateNodesFromDOM(editor, dom);
          root.append(...nodes);
        } else {
          const paragraph = $createParagraphNode();
          const textNode = $createTextNode(initialText);
          paragraph.append(textNode);
          root.append(paragraph);
        }
      });
      setHasInitialized(true);
    }
  }, [editor, initialText, hasInitialized]);

  return null;
}

export default InitialTextPlugin;
