import React, { useCallback, useMemo, useState } 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";
window.katex = katex;

// Add sizes to whitelist and register them
const Size = Quill.import("formats/size");
Size.whitelist = ["extra-small", "small", "medium", "large"];
Quill.register(Size, true);

// Add fonts to whitelist and register them
const Font = Quill.import("formats/font");
Font.whitelist = [
  "arial",
  "comic-sans",
  "courier-new",
  "georgia",
  "helvetica",
  "lucida"
];
Quill.register(Font, true);

const toolbarOptions = [
  [{ header: 1 }, { header: 2 }],
  ["bold", "italic", "underline", "strike", "blockquote"],
  [{ list: "ordered" }, { list: "bullet" }, { indent: "-1" }, { indent: "+1" }],
  ["link", "image", "formula"],
  ["clean"]
];

// Formats objects for setting up the Quill editor
export const formats = [
  "header",
  "font",
  "size",
  "bold",
  "italic",
  "underline",
  "align",
  "strike",
  "script",
  "blockquote",
  "background",
  "list",
  "bullet",
  "indent",
  "link",
  "image",
  "color",
  "code-block"
];

// Quill Toolbar component
export const QuillToolbar = ({ anchorRef = undefined, defaultValue, setProperties, idTool, toolbarContainerLoaded, placeholder }) => {

  const [state, setState] = useState({ value: "" });

  const handleChange = (value) => {
    setState({ value });
    // if its detail-1, then the value is for title,
    // or else the value goes to explanation.
    idTool === "detail-1" ? setProperties(prev => ({ ...prev, title: value }))
      : setProperties(prev => ({ ...prev, answer_explanation: value }));
  };

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

  const formats = [
    "header",
    "bold",
    "italic",
    "underline",
    "strike",
    "blockquote",
    "list",
    "bullet",
    "indent",
    "link",
    "image",
    "formula"
  ];

  React.useEffect(() => {
    setState({value: defaultValue});
    return () => {
      const parentOG = document.querySelector(`#${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(`#${idTool} .ql-toolbar`);

    toolbarSection.appendChild(element);
  }

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

  return (
    <>
      {toolbarContainerLoaded && <div>
        <ReactQuill
          ref={anchorRef}
          id={idTool}
          // defaultValue={defaultValue}
          theme="snow"
          value={state.value}
          onChange={handleChange}
          placeholder={placeholder}
          modules={modules}
          formats={formats}
          onFocus={focusFunction}
          onBlur={lostFocusFunction}
        />
      </div>}
    </>
  );
};

export default QuillToolbar;
