import React, { useRef, useCallback } from "react";
import { SimpleMdeReact } from "react-simplemde-editor";
import MathQuillContainer from "./MathQuillContainer";


const SimpleEditor = (props) => {
    const {idName, setProperties, toolbarContainerLoaded = true} = props;
    const [modalOpen, setModalOpen] = React.useState(false);
    
    const editorRef = useRef();
    // easyMDE instance ref
    const easyMde = useRef(null);


    const [value, setValue] = React.useState(
        props.defaultValue
    );

    const onChange = React.useCallback((value) => {
        setValue(value);
        idName === "question-detail" ? setProperties(prev => ({ ...prev, title: value }))
            : setProperties(prev => ({ ...prev, answer_explanation: value }));
    }, []);

    const toolbarSummon = React.useCallback((e) => {
        e.stopPropagation();
        let editorsToolbar = document.querySelectorAll(".editor-toolbar");
        for(let i of editorsToolbar) {
            // i.style.display = "none";
            i.style.maxHeight = "0";
            i.style.paddingBlock = "0";
            i.style.opacity = "0";
        }
        let editorTool = document.querySelector(`#${easyMde.current.element.id}-wrapper .editor-toolbar`);
        // editorTool.style.display = "block";
        editorTool.style.maxHeight = "200px";
        editorTool.style.paddingBlock = "9px";
        editorTool.style.opacity = "1";
    }, []);

    React.useEffect(() => {
        return () => {
            let editorElement = document.querySelector(`#${easyMde.current.element.id}-wrapper`);
            editorElement.removeEventListener('mousedown', toolbarSummon);
        }
    }, []);

    const getMdeInstanceCallback = useCallback((simpleMde) => {
        easyMde.current = simpleMde;
        let editorElement = document.querySelector(`#${easyMde.current.element.id}-wrapper`);

        editorElement.addEventListener('mousedown', toolbarSummon);
    }, []);

    const Options = React.useMemo(() => {
        return {
            // autofocus: true,
            spellChecker: false,
            status: false,
            placeholder: props.placeholder,
            minHeight: "100px",
            previewRender: (text) => {
                // first process the markdown
                const markdownHtml = easyMde.current.markdown(text);

                // typeset with MathJax
                const container = document.createElement("div");
                container.innerHTML = markdownHtml;
                props.mathJax.current.typesetClear([container]);
                props.mathJax.current.typeset([container]);
                return container.innerHTML;
            },
            toolbar: [
                {
                    name: "heading",
                    title: "Heading #3",
                    action: editor => {
                        const cm = editor.codemirror;
                        const text = cm.getSelection();
                        cm.replaceSelection("### "+text);
                    },
                    className: "fa fa-header"
                },
                "bold", "italic",
                "|",
                "code", "unordered-list", "ordered-list",
                "|",
                "table", "link",
                "|",
                "clean-block","preview", "fullscreen", "side-by-side",
                "|",
                "undo", "redo",
                {
                    name: "formula-button",
                    title: "Math Expression",
                    action: (editor) => {
                        const cm = editor.codemirror;
                        editorRef.current = cm;
                        setModalOpen(true);
                    },
                    className: "fa fa-calculator"
                }
            ]
            // toolbar: false
        };
    }, []);

    return (
        <>{toolbarContainerLoaded && <>
            <SimpleMdeReact
                className="some-editor"
                id={props.idName}
                value={value}
                onChange={onChange}
                options={Options}
                getMdeInstance={getMdeInstanceCallback}
            />
            {modalOpen && (
                <MathQuillContainer onClose={setModalOpen} codemirror={editorRef} easymde={easyMde.current}/>
            )}
        </>}</>
    );
};

export default SimpleEditor;