import React, { useState, useCallback, useEffect } from 'react';
import { flushSync } from 'react-dom';
import { EditorContent, useEditor } from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';
import { HighlightTextExtension } from './HighlightText';

interface MainEditorProps {
  content: any[];
  onChangeContent?: (content: any[]) => void;
}

export default function MainEditor({ content, onChangeContent }: MainEditorProps) {
  const [renderContent, setRenderContent] = useState<any[]>(content);

  useEffect(() => {
    onChangeContent?.(renderContent);;
  }, [renderContent]);

  const editor = useEditor({
    extensions: [
      StarterKit,
      HighlightTextExtension,
    ],
    content: { type: 'doc', content: renderContent },
    editorProps: {
      attributes: {
        class: 'prose prose-invert max-w-none focus:outline-none'
      }
    },
    immediatelyRender: false,
    onCreate: ({ editor }) => {
      editor.setOptions({ editable: true })
    },
    onUpdate: ({ editor }) => {
      const json = editor.getJSON();
      flushSync(() => {
        setRenderContent(json.content);
      });
    },
  });

  if (!editor) {
    return null
  }
  return (
    <EditorContent editor={editor} />
  );
}