import { FC, useEffect } from 'react';
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
import { useReactiveVar } from '@apollo/client';
import { isEditingMessageVar } from 'state-management/chat';
import { MessageFragment } from 'expo-schema';
import { getLexicalRootByChildren, LexicalChildrenTypes, lexicalTextChild } from 'utils/richText';

export const EditMessage: FC<EditMessageProps> = ({ message }) => {
  const [editor] = useLexicalComposerContext();
  const isEditingMessage = useReactiveVar(isEditingMessageVar);
  const isLoadMessageIntoChatInput =
    isEditingMessage && message && message?.richTextContent && message?.richTextContent?.length > 0;

  useEffect(() => {
    if (isLoadMessageIntoChatInput) {
      if (message?.richTextContent?.length) {
        const children = message?.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))
        );
        editor.setEditorState(initialState);
        editor.focus();
      }
    }
  }, [editor, isEditingMessage, isLoadMessageIntoChatInput, message, message?.richTextContent]);

  useEffect(() => {
    if (!isEditingMessage) {
      const initialState = editor.parseEditorState(JSON.stringify(getLexicalRootByChildren([])));
      editor.setEditorState(initialState);
      editor.focus();
    }
  }, [editor, isEditingMessage, isLoadMessageIntoChatInput]);

  return <></>;
};

interface EditMessageProps {
  message: MessageFragment | undefined;
}
