import React, { useState, useRef } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import { Button, Layout, Typography, Radio, notification, Modal, Spin } from 'antd';
import _ from 'lodash';
import SimpleEditor from './createQuestion2test/MDEditor';
import { LoadingOutlined, UploadOutlined } from '@ant-design/icons';
import "quill/dist/quill.snow.css";
import "easymde/dist/easymde.min.css";
import './createQuestion2test/createQuestion.css';
import { selectorService } from '../../services/selectorService';
import { authenticationService } from '../../_services';
import SelectorNew from './SelectorNew';
import OpR from './createQuestion2test/OpR';
import OpC from './createQuestion2test/OpC';
import OptionsBoolean from './createQuestion2test/OptionsBoolean';
import UploadQuestionModal from './uploadQuestion/UploadQuestionModal';
import { useTranslation } from 'react-i18next';

const complexityOptions = [
    {
        label: 'Easy',
        value: 1,
    },
    {
        label: 'Medium',
        value: 2,
    },
    {
        label: 'Difficult',
        value: 3,
    },
];

const CreateQuestion2 = ({ language, mathJax }) => {

    const location = useLocation();
    const history = useHistory();
    const {t} = useTranslation();

    const [data, setdata] = useState({});

    // ref for mathjax context to use in children
    // const mj = useRef(null);
    // const mathJaxContext = useContext(MathJaxBaseContext)

    const [uploadMode, setUploadMode] = useState({ isOpen: false });
    const [editResourceLoaded, setEditResourceLoaded] = useState({ check: false, mode: 1 });

    const [toolbarContainerLoaded, checkToolbarContainerLoad] = useState(false);

    const [submitting, setSubmitting] = useState(false);
    const anchorRef = useRef(); // to catch the title editor to refocus when changing question types and prevent onBlur bug that hiding the editor toolbar causes.

    const cls = useRef(authenticationService.currentClassValue);
    //category about the question
    const [selectorVariables, setSelectorVariables] = useState({
        subject: "",
        category: "", // this is same as topic thats referred to in UI
        questionType: "",
    });

    //properties of the question
    const [properties, setProperties] = useState({
        language: authenticationService.currentUserValue.language_code || "",
        complexity_code: "",
        title: "",
        answer_explanation: ""
    });

    // Data from option boxes
    const actualOptionData = useRef([{ text: "", isCorrect: false }, { text: "", isCorrect: false }]);

    const [sectionName, setSectionName] = useState("");  // name of the section

    React.useEffect(() => {
        async function fetchQuestionFromServer() {
            if (location.rowState?.key && location.rowState.status === "DRAFT") {
                setSubmitting(true);    // just to make loading modal show up
                const res = await selectorService.getQuestion(location.rowState.key);
                // console.log(res);
                /*
                    answer_explanation: ""
                    author_id: 80
                    author_name: "EduTech"
                    complexity_code: 2
                    id: 2105
                    isActive: true
                    isBookmarked: null
                    languages_available: Array [ 1 ]
                    last_updated: "2022-11-17T04:59:56.13"
                    options: Array [ {…}, {…} ]
                    source: "Manual Entry"
                    status: "DRAFT"
                    subject_id: 1
                    subject_name: "General Awareness"
                    tags: null
                    title: "<p>In which year was India partitioned?</p>"
                    topic_id: 1
                    topic_name: "History of India"
                    type: "MCQ"
                    type_name: "Multiple Choice Questions"
                */
                setSelectorVariables({
                    subject: res.result.subject_id,
                    category: res.result.topic_id,
                    questionType: res.result.type
                });
                setProperties(prev => ({
                    ...prev,
                    complexity_code: res.result.complexity_code,
                    title: res.result.title,
                    answer_explanation: res.result.answer_explanation
                }));
                actualOptionData.current = res.result.options;

                setSubmitting(false);
                setEditResourceLoaded({ check: true, mode: 1 });
            } else {
                setSectionName(t('uploadQuestion.uploadQuesType'));
                setEditResourceLoaded({ check: true, mode: -1 });
            }
        }
        fetchQuestionFromServer();
        
        // listen to mousedown event to hide all the toolbar from editors
        function listenEvent(e) {
            // console.log(e) //dev-log
            if (e.target.className === "ant-radio-input" || 
                e.target.className === "ant-radio-wrapper" || 
                e.target.className === "radio-wrapper center-flex" || 
                e.target.className === "options-box" || 
                e.target.className === "ant-radio ant-radio-checked" ||
                e.target.className === "ant-checkbox-input" ||
                e.target.className === "ant-checkbox-wrapper" ||
                e.target.className === "ant-checkbox-wrapper ant-checkbox-wrapper-checked" ||
                e.target.className === "ant-checkbox-group" ||
                e.target.className === "ant-radio-group") return;
            if (e.target.localName === "button") return;
            if (e.target.className === "formula-generator-wrapper") return;
            if (e.target.className === "formula-display-frame" || e.target.className === "formula-input") return;
            if (e.target.firstChild?.data === "More Option Input") return;
            let editorsToolbar = document.querySelectorAll(".editor-toolbar");
            for (let i of editorsToolbar) {
                i.style.maxHeight = "0";
                i.style.paddingBlock = "0";
                i.style.opacity = "0";
            }
        }
        document.addEventListener('mousedown', listenEvent);
        return () => document.removeEventListener('mousedown', listenEvent);
    }, []);

    React.useEffect(() => {
        if (selectorVariables.questionType && anchorRef.current) {
            // anchorRef.current.focus(); // this was an attempt to bring focus to Question Detail editor, but the logic didnt work out in the end so dropped it.
            // But left this code as a future reference if its needed.

            checkToolbarContainerLoad(false);
            setProperties(prev => ({ ...prev, complexity_code: "", answer_explanation: "" }));
            actualOptionData.current = [{ text: "", isCorrect: false }, { text: "", isCorrect: false }];
            setTimeout(() => checkToolbarContainerLoad(true), 100);
        }
        if (!selectorVariables.questionType) {
            checkToolbarContainerLoad(false);
            actualOptionData.current = [{ text: "", isCorrect: false }, { text: "", isCorrect: false }];
        }
        if (selectorVariables.questionType && !anchorRef.current) {
            checkToolbarContainerLoad(true);
        }
    }, [selectorVariables.questionType]);

    function handleSelection(property, value = "", objectName = t('uploadQuestion.warning8')) {
        if (property === "questionType") {
            objectName.children ? setSectionName(objectName?.children)
                : setSectionName(t('uploadQuestion.uploadQuesType'));
        }
        setSelectorVariables(prevVal => ({
            ...prevVal,
            [property]: value,
        }));
    }

    function renderOption() {
        switch (selectorVariables.questionType) {
            case "MCQ":
                return <OpR mathJax={mathJax} actualOptionData={actualOptionData} toolbarContainerLoaded={toolbarContainerLoaded} />;
            case "MRQ":
                return <OpC mathJax={mathJax} actualOptionData={actualOptionData} toolbarContainerLoaded={toolbarContainerLoaded} />;
            case "TNF":
                return <OptionsBoolean actualOptionData={actualOptionData} />;
            case "SUB":
                return;
            default:
                return <h4>This is messed up bro...</h4>
        }
    }

    function collectInfo(status) {
        let validate;
        // checking if subject and topic and question types are selected from dropdown at the top
        if (!selectorVariables.subject || !selectorVariables.category || !selectorVariables.questionType) {
            status === "PUBLISHED" ? notification.error({ message: t('uploadQuestion.warning0') })
                : notification.error({ message: t('uploadQuestion.warning1') });
            return;
        }

        if (status === "DRAFT") {    // this check is only meant for question that is being sent to DRAFT status
            if (!properties.title || !properties.language || !properties.complexity_code) {
                notification.error({ message: t('uploadQuestion.warning2') });
                return;
            }
        }

        if (status === "PUBLISHED") {    // this check is only meant for question which is being published (as in getting Submitted)
            if (!properties.title || !properties.language || !properties.answer_explanation || !properties.complexity_code) {
                notification.error({ message: t('uploadQuestion.warning3') });
                return;
            }
            let s = properties.title;
            let t = s.replace(new RegExp('<[^>]*>', 'g'), ''); // this replaces all HTML tag with "" [empty string]
            t = t.replace(" ", "");
            if (!t) {
                notification.error({ message: t('uploadQuestion.warning4') });
                return;
            }
            s = properties.answer_explanation;
            t = s.replace(new RegExp('<[^>]*>', 'g'), ''); // this replaces all HTML tag with "" [empty string]
            t = t.replace(" ", "");
            if (!t) {
                notification.error({ message: t('uploadQuestion.warning5') });
                return;
            }
        }

        if (selectorVariables.questionType !== "SUB") {
            // the above condition makes it so that when question type is set to subjective,
            // there will be no check for Options because Subjective questions don't have options.

            validate = actualOptionData.current.filter(item => item.isCorrect);
            // checking if one or more correct answers is/are selected.
            if (validate.length === 0 && status !== "DRAFT") {
                notification.error({ message: t('uploadQuestion.warning5') });
                return;
            }
            validate = actualOptionData.current.filter(item => (item.text ? true : false));
            // checking if a question exist in all the option blanks created.
            if (validate.length !== actualOptionData.current.length && status !== "DRAFT") {
                notification.error({ message: t('uploadQuestion.warning6') });
                return;
            }

        }
        submit({ ...properties, options: actualOptionData.current, ...selectorVariables, status }); // sending all validated info to submit function now
    }

    async function submit({ questionType: type, category: topic_id, complexity_code, title, answer_explanation, options, status }) {
        // REQUEST BODY
        // {
        //    "type": "string",
        //    "topic_id": 0,
        //    "complexity_code": 0,
        //    "status": "string", // need to add
        //    "title": "string",
        //    "description": "string", // uhhhh???
        //    "answer_explanation": "string",
        //    "source": "string", // need to add
        //    "options": [
        //      {
        //        "text": "string",
        //        "isCorrect": true
        //      }
        //    ]
        // }
        // options not needed in case of SUBJECTIVE question types.

        if (status === "DRAFT" && type !== "SUB") {
            options = options.filter(option => {
                if (option.text) {
                    return true;
                }
            });
        }
        let submitObject;
        submitObject = type !== "SUB" ? { type, topic_id, complexity_code, title, answer_explanation, options, status }
            : { type, topic_id, complexity_code, title, answer_explanation, status };
        submitObject.source = "Manual Entry";
        try {
            setSubmitting(true);

            if (editResourceLoaded.mode === 1) {
                submitObject.id = location.rowState.key;
                const response = await selectorService.editQuestion(location.rowState.key, submitObject);
                if (+response.status.code < 0) {
                    throw response.status.message || t('warningBasic');
                }
                status === "PUBLISHED" ? notification.success({ message: t('uploadQuestion.success1') })
                    : notification.success({ message: t('uploadQuestion.success2') });

                history.push("/draftQuestions");
                // setSubmitting(false);
            }

            if (editResourceLoaded.mode < 0) {
                const response = await selectorService.createQuestion(submitObject);
                if (response.status.code < 0) {
                    throw response.status.message || t('uploadQuestion.warningBasic');
                }
                status === "PUBLISHED" ? notification.success({ message: t('uploadQuestion.success1') })
                    : notification.success({ message: t('uploadQuestion.success2') });
                setSubmitting(false);

                // reset the inputs after successful submit
                checkToolbarContainerLoad(false);
                setProperties({ language: authenticationService.currentUserValue.language_code || "", complexity_code: "", title: "", answer_explanation: "" });
                actualOptionData.current = [{ text: "", isCorrect: false }, { text: "", isCorrect: false }];
                setTimeout(() => checkToolbarContainerLoad(true), 100);
            }
        } catch (err) {
            err && notification.error({ message: err });
            setSubmitting(false);
        }
    }

    function openUploadModal() {
        setUploadMode({ isOpen: true });
    }

    return (
            <Layout className='overflow-y--ready'>
                {/* <RepeatedData.Provider value={{data, setdata}}> */}
                    {editResourceLoaded.check && <Layout.Content prefixCls='create-question-2'>
                        <div className='section-header'>
                            <div className="left-side">
                                <SelectorNew serviceCall={selectorService.loadSubjects} pathActive={cls.current} handleSelection={handleSelection} property="subject"
                                    placeholder="Select a subject" chosenValue={selectorVariables.subject} />
                                <SelectorNew serviceCall={selectorService.loadCategory} pathActive={selectorVariables.subject} handleSelection={handleSelection} property="category"
                                    placeholder="Select a topic" chosenValue={selectorVariables.category} />
                                <SelectorNew serviceCall={selectorService.loadQuestionTypes} handleSelection={handleSelection} property="questionType"
                                    placeholder="Select the question type" chosenValue={selectorVariables.questionType} />
                            </div>
                            <div className="right-side">
                                <Button type='primary' onClick={() => openUploadModal()} icon={<UploadOutlined />}>
                                    {t('uploadQuestion.uploadQueTitle')}
                                </Button>
                            </div>
                        </div>
                        <div className="section-name">
                            <Typography.Title level={5}>{sectionName}</Typography.Title>
                        </div>
                        {sectionName !== t('uploadQuestion.uploadQuesType') && <div className="section-body-2">
                            <div className="toolbar-section"> </div> {/* this is tracked by toolbarContainerLoaded */}
                            <div className="user-input-section">

                                {/* <Typography.Text className='align--center' strong>Select Language :</Typography.Text>
                            <Select
                                size='normal'
                                // suffixIcon={<CaretDownOutlined />}
                                placeholder="Select language"
                                onChange={value => setProperties(prev => ({ ...prev, language: value }))}
                                value={properties.language || undefined}
                                style={{ minWidth: '150px' }}
                            >
                                {language.map(eachlang => {
                                    return <Select.Option key={eachlang.id} value={eachlang.code || eachlang.id}>{eachlang.name}</Select.Option>
                                })}
                            </Select> */}

                                <Typography.Text className='align--center' strong>{t('complex-header')} :</Typography.Text>
                                <Radio.Group
                                    options={complexityOptions}
                                    onChange={({ target: { value } }) => setProperties(prev => ({ ...prev, complexity_code: value }))}
                                    value={properties.complexity_code || undefined}
                                    optionType="button"
                                    buttonStyle="solid"
                                />

                                {toolbarContainerLoaded && <Typography.Text className='align--center' strong>{t('uploadQuestion.queDetail')} :</Typography.Text>}
                                {toolbarContainerLoaded && /*test*/
                                    <SimpleEditor
                                        idName="question-detail"
                                        defaultValue={properties.title}
                                        mathJax={mathJax}
                                        placeholder="Write your question here..."
                                        toolbarContainerLoaded={toolbarContainerLoaded}
                                        setProperties={setProperties}
                                    />
                                }

                                {selectorVariables?.questionType !== "SUB" && toolbarContainerLoaded && <Typography.Text className='pt-2-5' strong>{t('uploadQuestion.options')} :</Typography.Text>}
                                {renderOption()}

                                {toolbarContainerLoaded && <Typography.Text className='pt-1-0' strong>{t('uploadQuestion.explanation')} :</Typography.Text>}
                                {toolbarContainerLoaded && /*test*/
                                    <SimpleEditor
                                        idName="answer-explain"
                                        defaultValue={properties.answer_explanation}
                                        mathJax={mathJax}
                                        placeholder="Write the answer explanation here"
                                        toolbarContainerLoaded={toolbarContainerLoaded}
                                        setProperties={setProperties}
                                    />
                                }
                            </div>
                        </div>}
                    </Layout.Content>}
                    <div className="button-container">
                        <Button disabled={submitting} onMouseDown={() => collectInfo("DRAFT")}>{t('save-btn')}</Button>
                        <Button type='primary' disabled={submitting} onMouseDown={() => collectInfo("PUBLISHED")}>{t('submit-btn')}</Button>
                    </div>
                    <Modal open={submitting} visible={submitting} width={108} maskClosable={false} keyboard={false} closable={false} centered footer={null} >
                        <Spin indicator={<LoadingOutlined style={{ fontSize: 60 }} spin />} />
                    </Modal>

                    <div className="upload-question-modal">
                        <UploadQuestionModal uploadMode={uploadMode} setUploadMode={setUploadMode} />
                    </div>
                {/* </RepeatedData.Provider> */}
            </Layout>
    );
}

export default CreateQuestion2;
