import React, { useCallback, useMemo, useRef } from "react";
import ReactQuill, { Quill } from "react-quill";
import katex from "katex";
import "katex/dist/katex.min.css";
import "react-quill/dist/quill.snow.css";
import { useState } from "react";
window.katex = katex;

const toolbarOptions = [
  ["bold", "italic", "underline"],
  ["formula"],
  ["clean"]
];

// Quill Toolbar component
export const QuillToolbarOption = ({ idTool, actualOptionData, defaultValue, toolbarContainerLoaded }) => {

  const [valueEditor, setValue] = useState();

  React.useEffect(() => {
    if (actualOptionData.current[idTool] && actualOptionData.current[idTool].text) {
      setValue(actualOptionData.current[idTool].text);
    }
    if (actualOptionData.current[idTool] && !actualOptionData.current[idTool].text) {
      setValue("");
    }
  }, [actualOptionData.current.length]);

  const handleChange = (value) => {
    setValue(value);
    actualOptionData.current[idTool] = {
      text: value,
      isCorrect: actualOptionData.current[idTool].isCorrect || false
    }
  };

  const modules = useMemo(
    () => ({
      formula: true,
      toolbar: {
        container: toolbarOptions
      }
    }),
    []
  );

  const formats = [
    "bold",
    "italic",
    "underline",
    "formula"
  ];

  React.useEffect(() => {
    return () => {
      const parentOG = document.querySelector(`#option-${idTool}`);
      const elementPrevious = document.querySelector(`.toolbar-section .ql-toolbar`);
      elementPrevious && parentOG && parentOG.insertBefore(elementPrevious, parentOG.firstChild);
    }
  }, []);

  function focusFunction() {
    const toolbarSection = document.querySelector(".toolbar-section");
    const element = document.querySelector(`#option-${idTool} .ql-toolbar`);

    toolbarSection.appendChild(element);

  }

  function lostFocusFunction() {
    const parentOG = document.querySelector(`#option-${idTool}`);
    const elementPrevious = document.querySelector(`.toolbar-section .ql-toolbar`);
    parentOG && elementPrevious && parentOG.insertBefore(elementPrevious, parentOG.firstChild);
  }

  return (
    <>
      {toolbarContainerLoaded && <div>
        <ReactQuill
          // defaultValue={actualOptionData.current[idTool].text || ""}
          id={`option-${idTool}`}
          theme="snow"
          value={valueEditor}
          onChange={handleChange}
          placeholder={"Write the option here..."}
          modules={modules}
          formats={formats}
          onFocus={focusFunction}
          onBlur={lostFocusFunction}
        />
      </div>}
    </>
  );
};

export default QuillToolbarOption;
