import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
import { MessageFragment } from 'expo-schema';
import { FC, useEffect, useState } from 'react';
import { getLexicalRootByChildren, LexicalChildrenTypes, lexicalTextChild } from 'utils/richText';
import { useParams } from 'react-router-dom';

export const LoadDraft: FC<LoadDraftProps> = ({ draft }) => {
  const [firstRendered, setFirstRendered] = useState(false);
  const [editor] = useLexicalComposerContext();
  const params = useParams();

  useEffect(() => {
    if (params.id) {
      setFirstRendered(false);
    }
  }, [params.id]);

  useEffect(() => {
    if (!firstRendered && draft) {
      if (draft.richTextContent?.length) {
        const children = draft.richTextContent[0].strings?.map((str) => {
          return {
            ...lexicalTextChild,
            type: str.onNewLine ? LexicalChildrenTypes.LineBreak : LexicalChildrenTypes.Text,
            text: str.value,
          };
        });
        const initialState = editor.parseEditorState(
          JSON.stringify(getLexicalRootByChildren(children))
        );
        setFirstRendered(true);
        editor.setEditorState(initialState);
        editor.focus();
      }
    }
  }, [draft, editor, firstRendered]);

  useEffect(() => {
    if (!draft) {
      const initialState = editor.parseEditorState(JSON.stringify(getLexicalRootByChildren([])));
      editor.setEditorState(initialState);
      setFirstRendered(false);
      editor.focus();
    }
  }, [draft, editor, firstRendered]);

  return <></>;
};

interface LoadDraftProps {
  draft: MessageFragment | undefined;
}
