import { Button, Layout, Radio, Select, Space, Spin, Typography, notification } from 'antd';
import React, { useState, useEffect, useRef } from 'react';
import { useLocation } from 'react-router-dom';
import './TranslateQuestion.css';
import { selectorService } from '../../services/selectorService';
import { MathJax } from 'better-react-mathjax';
import Markdown from 'marked-react';
import SimpleEditor from './createQuestion2test/MDEditor';
import { RepeatedData } from '../RepeatedDataProvider';
import OpRadio from './translateQuestion/OpRadio';
import { questionValidator } from './translateQuestion/validationSchema';
import { Loading3QuartersOutlined } from '@ant-design/icons';
// import { questionObjValidation } from './translateQuestion/validationSchema';

const primaryblue = "#3b3cea";

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

const TranslateQuestion = ({ language }) => {

    const { data } = React.useContext(RepeatedData);

    const location = useLocation();
    const languages = language;

    const getKey = location.state.key;

    const [valueOfLanguageChoice, setLanguageChoice] = useState(-1);
    const [properties, setProperties] = useState({
        complexity_code: 1,
        title: "",
        options: [],
        answer_explanation: ""
    });
    const actualTranslatedData = useRef([]);
    const [transProperties, setTransProperties] = useState({
        language_code: "",
        title: "",
        answer_explanation: ""
    });

    const [loadingQuestion, setLoading] = useState(true);

    useEffect(() => {
        // fetchQuestionData();
        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);
    }, []);

    async function fetchQuestionData() {
        const foundLanguageObj = languages.find(lang => lang.id === valueOfLanguageChoice);
        const response = await selectorService.getQuestion(getKey, foundLanguageObj.code);
        const result = response.result;
        setProperties(prev => ({
            ...prev,
            complexity_code: result.complexity_code,
            title: result.title,
            options: result.options,
            answer_explanation: result.answer_explanation
        }));
        setLoading(false);
    }

    const languageAvailableList = location.state.translated.map(lang => {
        const langObj = languages.find(langItem => (langItem.id === lang));
        return { label: langObj.name, value: langObj.id }
    });

    useEffect(() => {
        valueOfLanguageChoice < 0 && setLanguageChoice(languageAvailableList[0].value);
        if(valueOfLanguageChoice > 0) {
            setLoading(true);
            fetchQuestionData();
        }
    }, [valueOfLanguageChoice]);

    function onClickLanguageChange(val) {
        setTransProperties(prev => ({ ...prev, language_code: val }))
    }

    function languageShowChange({ target }) {
        setLanguageChoice(target.value)
    }

    const renderer = {
        paragraph(text) {
            return <MathJax key={"math-fromula"}>{text}</MathJax>
        },
        html(text) {
            return <span key={"title-span"}>{text}</span>;
        }
    }

    const handleSubmit = async (status = "DRAFT") => {
        // {
        //     "language_code": "string",
        //     "title": "string",
        //     "answer_explanation": "string",
        //     "options": [
        //       {
        //         "id": 0,
        //         "text": "string"
        //       }
        //     ]
        // }
        properties.options.forEach((opt, index) => {
            actualTranslatedData.current[index] = {
                ...actualTranslatedData.current[index],
                id: opt.id
            }
        });
        const submitData = {
            language_code: transProperties.language_code,
            title: transProperties.title,
            answer_explanation: transProperties.answer_explanation,
            options: [...actualTranslatedData.current]
        }
        try {
            process.env.NODE_ENV === "development" && console.log(getKey);
            const data = await questionValidator(properties.options.length, submitData);
            process.env.NODE_ENV === "development" && console.log(data);
            const res = await selectorService.cloneQuestionToLanguage(getKey, data);
            if(!res || res.status.code < 0) {
                throw "Fatal Error."
            }
            if(res.status.code > 0) {
                notification.success({
                    message: "Operation successful, question has been translated."
                });
            }
        } catch (error) {
            process.env.NODE_ENV === "development" && console.log(error.issues)
            if(!error.issues) {
                notification.error({
                    message: "Operation unsuccessful. Question was not translated. Please try again.",
                    duration: 0
                });
                return;
            }
            if(error && error?.issues[0] && error.issues[0].path[0] === "language_code") {
                notification.error({
                    message: error.issues[0].message,
                    duration: 0
                });
                return;
            }
            if(error && error?.issues[0] && error.issues[0].path[0] === "options") {
                notification.error({
                    message: error.issues[0].message,
                    duration: 0
                });
                return;
            }
            notification.error({
                message: "Operation unsuccessful. Question was not translated. Please try again.",
                duration: 0
            });
        }
    }

    return (
        <Layout>
            <Layout.Content prefixCls='translate-question'>
                {/* <Space direction={"vertical"} size={24}> */}
                {(languages && language.length < 1) || loadingQuestion && <Loading3QuartersOutlined spin style={{fontSize: 32}} />}
                    <div className='translate-question--body' style={
                        {display: (languages && language.length < 1) || loadingQuestion? "none" : "block"}
                    }><div className='spacer--24'>
                        <div className="section-name">
                            <Typography.Title level={5}>Translate Question</Typography.Title>
                        </div>
                        <div className='language-choice columnar-layout-label-240'>
                            <Typography.Text strong style={{ color: primaryblue, width: 120 }}>Available Language</Typography.Text>
                            <Radio.Group
                                options={languageAvailableList}
                                value={valueOfLanguageChoice}
                                defaultValue={languageAvailableList && languageAvailableList[0].value}
                                optionType='button'
                                buttonStyle='solid'
                                onChange={languageShowChange}
                            />
                        </div>
                        <div className='translated-lang columnar-layout-label-240'>
                            <Typography.Text strong style={{ color: primaryblue }}>Translate to</Typography.Text>
                            <Select size='normal' placeholder={<>Select Language</>} optionLabelProp="label"
                                dropdownRender={(menu) => {
                                    return (
                                        <>
                                            {languages.length > 0 ? <>{menu}</> :
                                                <>
                                                    <Space style={{ display: 'flex', justifyContent: 'center', flexDirection: 'column', padding: 10 }}>
                                                        <Spin />
                                                        Loading languages, please wait...
                                                    </Space>
                                                </>
                                            }
                                        </>
                                    );
                                }}
                                onChange={onClickLanguageChange}
                                value={transProperties.language_code || undefined}
                                style={{ minWidth: '250px', maxWidth: '270px' }}
                            >
                                {languages.map((languageItem, index) => {
                                    const check = location.state.translated.find(langItem => (langItem + "" === languageItem.id + ""));
                                    return !check && (
                                        <Select.Option key={languageItem.code}
                                            label={
                                                <>
                                                    &nbsp;
                                                    {languageItem.name}
                                                </>
                                            }>
                                            {languageItem.name}
                                        </Select.Option>
                                    );
                                })}
                            </Select>
                        </div>
                        <div className='translate-question--innerbody spacer--24'>
                            <div className='complexity-choice columnar-layout-label-240'>
                                <Typography.Text strong style={{ color: primaryblue }}>Complexity</Typography.Text>
                                <Radio.Group
                                    options={complexityOptions}
                                    // onChange={({ target: { value } }) => setProperties(prev => ({ ...prev, complexity_code: value }))}
                                    value={properties.complexity_code || undefined}
                                />
                            </div>
                            <div className='question-detail columnar-layout-label-240'>
                                <Typography.Text strong style={{ color: primaryblue, alignSelf: 'start', paddingTop: 8 }}>Question Details</Typography.Text>
                                <div className='spacer--16'>
                                    <div className='question-preview-lang'>
                                        <Markdown key={"question-title"} renderer={renderer}>
                                            {properties.title}
                                        </Markdown>
                                    </div>
                                    <SimpleEditor idName="question-detail"
                                        // defaultValue={properties.title}
                                        mathJax={data.mathJax}
                                        placeholder="Write the translation of question here..."
                                        toolbarContainerLoaded={!loadingQuestion}
                                        setProperties={setTransProperties}
                                    />
                                </div>
                            </div>
                            {(languages && language.length < 1) || loadingQuestion? <div>Loading Options...</div>
                            :<div className='question-options columnar-layout-label-240'>
                                <Typography.Text strong style={{ color: primaryblue, alignSelf: 'start', paddingTop: 8 }}>Options</Typography.Text>
                                <div className='option-boxes'>
                                    <OpRadio actualTranslatedData={actualTranslatedData}
                                        options={properties.options}
                                    />
                                </div>
                            </div>}
                            <div className='question-explanation columnar-layout-label-240'>
                                <Typography.Text strong style={{ color: primaryblue, alignSelf: 'start', paddingTop: 8 }}>Explanation</Typography.Text>
                                <div className='spacer--16'>
                                    <div className='question-preview-lang'>
                                        <Markdown key={"question-explanation"} renderer={renderer}>
                                            {properties.answer_explanation}
                                        </Markdown>
                                    </div>
                                    <SimpleEditor idName="question-explanation-editor"
                                        // defaultValue={properties.title}
                                        mathJax={data.mathJax}
                                        placeholder="Write the translation of explanation here..."
                                        toolbarContainerLoaded={!loadingQuestion}
                                        setProperties={setTransProperties}
                                    />
                                </div>
                            </div>
                        </div>
                    </div></div>
                {/* </Space> */}
            </Layout.Content>
            <div className='button-container'>
                <Button loading={loadingQuestion} onClick={handleSubmit}>Save</Button>
                <Button loading={loadingQuestion} onClick={handleSubmit} type='primary'>Publish</Button>
            </div>
        </Layout>
    );
}

export default TranslateQuestion;
