import { Button, Checkbox, Drawer, Radio, Typography } from 'antd';
import React, { useState, useEffect, useRef, useContext, useLayoutEffect } from 'react';
import { MathJax } from 'better-react-mathjax';
import Markdown from 'marked-react';
import { selectorService } from '../../services/selectorService';
import './QuestionDrawer.css';
import { LoadingOutlined } from '@ant-design/icons';
import { RepeatedData } from '../RepeatedDataProvider';


const QuestionDrawer = (props) => {

    // const { data: {mathJax} } = useContext(RepeatedData);

    const mounted = useRef(true);
    const [openState, setOpen] = useState(props.visible);
    const [loading, setLoading] = useState(false);
    const [questionArtifact, setQuestion] = useState({
        type: "",
        type_code: "",
        title: "",
        explanation: "",
        complexity: -1,
        options: [],
        authorName: "",
        subjectName: "",
        categoryName: "",
        translatedTo: []
    });

    const {languageInfoVisible = true} = props;

    useEffect(() => {
        mounted.current = true;
        setLoading(true);
        // console.log("trigger", props.recordData);
        if (openState) {
            fetchQuestionDetail();
        }
        if (!openState) {
            props.setVisible();
        }

        return () => {
            mounted.current = false;
        }
    }, [props.visible, openState, props.recordData]);

    async function fetchQuestionDetail() {
        try {
            const questionDetails = await selectorService.getQuestion(props.recordData.key);
            if (questionDetails && questionDetails.status?.code < 0) {
                setTimeout(() => props.setVisible(prev => ({ ...prev, visile: false })), 2000);
                throw "No question with the given ID found";
            }
            const { result } = questionDetails;
            mounted.current && setQuestion(() => ({
                type: result.type_name,
                type_code: result.type,
                title: result.title,
                explanation: result.answer_explanation,
                complexity: result.complexity_code,
                options: [...result.options],
                authorName: result.author_name,
                subjectName: result.subject_name,
                categoryName: result.topic_name,
                translatedTo: [...result.languages_available]
            }));
            mounted.current && setLoading(false);
        } catch (error) {
            console.log(error);
        }
    }

    const renderer = {
        paragraph(text) {
            // console.log("text =", text)
            return <MathJax key={text}>{text}</MathJax>
        },
        // heading(text, level) {
        //     console.log("head =", text)
        //     return false
        // }
        html(text) {
            return <span key={"title-span"}>{text}</span>;
        }
    }

    function determineComplexity() {
        if (questionArtifact.complexity === 1) {
            return "Easy";
        }
        if (questionArtifact.complexity === 2) {
            return "Medium";
        }
        if (questionArtifact.complexity === 3) {
            return "Difficult";
        }
        return "N/A"
    }

    function renderOptions(option, i) {
        if (questionArtifact.type_code === "MCQ") {
            return (
                <div key={"checkbox-" + i} className="option" data-correct-true={option.isCorrect && "1"}>
                    <Radio key={"checkbox-" + i} checked={option.isCorrect ? true : false}>
                        <Markdown renderer={renderer}>{option.text}</Markdown>
                    </Radio>
                </div>
            );
        }
        if (questionArtifact.type_code === "MRQ") {
            return (
                <div key={"checkbox-" + i} className="option" data-correct-true={option.isCorrect && "1"}>
                    <Checkbox key={"checkbox-" + i} checked={option.isCorrect ? true : false}>
                        <Markdown renderer={renderer}>{option.text}</Markdown>
                    </Checkbox>
                </div>
            );
        }
        if (questionArtifact.type_code === "TNF") {
            return (
                <div key={"checkbox-" + i} className="option" data-correct-true={option.isCorrect && "1"}>
                    <Radio key={"checkbox-" + i} checked={option.isCorrect ? true : false}>
                        <Markdown renderer={renderer}>{option.text}</Markdown>
                    </Radio>
                </div>
            );
        }

        return <>
            <div>Option types not defined properly.</div>
            <div>Please contact the developer.</div>
        </>
    }

    function languageTag(langID) {
        const languages = props.language;
        if(languageInfoVisible === false) {
            return <></>
        }
        if (!languages) {
            return <div>Module not loaded properly, please reload</div>
        }
        // const o = [];
        // if(!questionArtifact.translatedTo || questionArtifact.translatedTo.length < 1) {
        //     return <div>No languages found for this question.</div>
        // }
        let p = languages.find(lang => (lang.id === langID));
        if (p?.name) {
            // o.push(p.name);
            return <div key={langID} className={"lang--tag"}>
                {p.name}
            </div>
        } else {
            return <div>The language information is not correct in this question.</div>
        }
        // const languageString = o.join(", ");
        // return languageString;
    }

    return (
        <>
            <Drawer
                className='question--drawer'
                title={"Question Number "+ props.number}
                placement="right"
                width={600}
                onClose={() => setOpen(false)}
                footer={
                    <div
                        style={{
                            textAlign: "left",
                        }}
                    >
                        <Button
                            className='mr-0-5'
                            onClick={props.handlePreviousButton}
                            type="primary"
                            disabled={props.disablePrev}
                        >
                            Previous Question
                        </Button>
                        <Button onClick={props.handleNextButton} type="primary"
                            disabled={props.disableNext}>
                            Next Question
                        </Button>
                    </div>
                }
                // visible is used in this version of antd. In later version, it has been changed to 'open'
                visible={props.visible}
            >
                <div style={{ display: loading ? "block" : "none" }}><LoadingOutlined spin /></div>
                <div style={{ display: loading ? "none" : "block" }}>
                    <div className='question--info'>
                        <div><Typography.Text style={{ flex: '1 0 100%' }} strong>
                            Topic: </Typography.Text>{questionArtifact.categoryName}
                        </div>
                        <div data-complexity={questionArtifact.complexity}>
                            <Typography.Text style={{ flex: '1 0 100%' }} strong>
                                Complexity: </Typography.Text>{determineComplexity()}
                        </div>
                        <div><Typography.Text style={{ flex: '1 0 100%' }} strong>
                            Author: </Typography.Text>{questionArtifact.authorName}
                        </div>
                    </div>
                    <main className='question--body'>
                        <div className='question--title-body'>
                            <div className='question--title-label'>Question:</div>
                            {<Markdown key={"question-title"} renderer={renderer}>
                                {questionArtifact.title}
                                {/* topic - {questionArtifact.categoryName} */}
                            </Markdown>}
                        </div>
                        <div className='question--options-body'>
                            <div className='question--options-label'>Options:</div>
                            {questionArtifact.options.map((option, i) => {
                                return renderOptions(option, i);
                            })}
                        </div>
                        <div className='question--explanation-body'>
                            <div className='question--explanation-label'>Explanation:</div>
                            {<Markdown key={"question-explaination"} renderer={renderer}>
                                {questionArtifact.explanation}
                            </Markdown>}
                        </div>
                    </main>
                    <footer>
                        {languageInfoVisible && <div>Languages this question is translated into:</div>}
                        {questionArtifact.translatedTo && questionArtifact.translatedTo.length < 1
                            ? <div>No info on languages this question might be translated into</div>
                            : questionArtifact.translatedTo.map(item => {
                                return languageTag(item);
                            })}
                    </footer>
                </div>
            </Drawer>
        </>
    );
}

export default QuestionDrawer;
