"use client";

import { useTheme } from "next-themes";

import {
  BlockNoteEditor,
  Block
} from "@blocknote/core";
import {
  BlockNoteView,
  useBlockNote
} from "@blocknote/react";
import "@blocknote/core/style.css";

interface EditorProps {
  onChange: (value: string) => void;
  initialContent?: string;
  editable?: boolean;
};

export const Editor= ({
  onChange,
  initialContent,
  editable
}: EditorProps) => {
  const { resolvedTheme } = useTheme();

  const editor: BlockNoteEditor = useBlockNote({
    editable,
    onEditorReady(editor) {
      //on converti l'html reçu en block pour l'afficher correctement dans l'éditeur
      const getBlocks = async () => {
        const blocks: Block[] = await editor.HTMLToBlocks(initialContent ? initialContent : "");
        editor.replaceBlocks(editor.topLevelBlocks, blocks);
      };
      getBlocks();
    },
    onEditorContentChange: (editor) => {
      //on converti le block en html pour l'enregistrer en bdd
      const saveBlocksAsHTML = async () => {
        const html: string = await editor.blocksToHTML(editor.topLevelBlocks);
        onChange(html);
      };
      saveBlocksAsHTML();
    }
  });
  
  return (
    <div>
      <BlockNoteView 
        editor={editor}
        theme={resolvedTheme === "dark" ? "dark" : "light"}
      />
    </div>
  )
}