"use client";

import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useRef,
} from "react";

const EditorMdContext = createContext();

export function EditorProvider({ children }) {
  const editor = useRef({});
  const element = useRef({});
  const defaultValue = useRef({
    list: {
      blocks: [
        {
          type: "list",
          data: {
            style: "ordered",
            meta: {
              counterType: "numeric",
            },
            items: [
              {
                content: "",
                meta: {},
                items: [],
              },
            ],
          },
        },
      ],
    },
  });

  const registerEditor = useCallback(
    ({ id, editor: editorInstance, element: elementInstance }) => {
      editor.current[id] = editorInstance;
      element.current[id] = elementInstance;
    },
    []
  );

  const unregisterEditor = useCallback((id) => {
    if (!editor.current?.[id]) return;

    const theEditor = editor.current[id];
    const isEditor = typeof theEditor.destroy === "function";

    delete editor.current[id];
    delete element.current[id];

    if (isEditor) {
      theEditor.destroy();
    }
  }, []);

  return (
    <EditorMdContext.Provider
      value={{
        editor,
        element,
        defaultValue: defaultValue.current,
        registerEditor,
        unregisterEditor,
      }}>
      {children}
    </EditorMdContext.Provider>
  );
}

export const useEditor = () => {
  const context = useContext(EditorMdContext);

  useEffect(() => {
    if (!context) {
      throw new Error("useEditor must be used within a EditorProvider");
    }
  }, [context]);

  return context;
};
