import React, { useState } from "react";
import { Checkbox, Button, notification } from 'antd';
import "easymde/dist/easymde.min.css";
import SimpleEditorOption from "./MDEditorOption";
import { MinusCircleFilled } from '@ant-design/icons';
import { useTranslation } from "react-i18next";

const OpC = ({ actualOptionData, toolbarContainerLoaded, mathJax }) => {

    const {t} = useTranslation();

    const [options, updateOptions] = useState(["_", "_"]);
    const [checkboxes, updateCheckboxes] = useState([]);

    React.useEffect(() => {
        for(let i = 2; i < actualOptionData.current.length; i++) {
            updateOptions(prev => [...prev, "_"]);
        }
        const positions = actualOptionData.current.map((option, indx) => {
            if (option.isCorrect) {
                return indx;
            }
        }).filter(item => {
            if(item) return true; else return false;
        }); 
        // @ts-ignore
        updateCheckboxes(() => [...positions]);
        return () => {
            updateOptions(["_", "_"]);
            updateCheckboxes([]);
            actualOptionData.current = [{text: "", isCorrect: false}, {text: "", isCorrect: false}];
        }
    }, []);

    React.useEffect(() => {
        if(!toolbarContainerLoaded) {
            updateOptions(["_","_"]);
            updateCheckboxes([]);
        }
    }, [toolbarContainerLoaded]);

    function addRadio() {
        let s; let t;
        if(!actualOptionData.current[0].text) {
            notification.info({ message: "Please fill up the previous option boxes before adding a new one" });
            return;
        }
        s = actualOptionData.current[0].text;
        t = s.replace(new RegExp('<[^>]*>', 'g'), ''); // this replaces all HTML tag with "" [empty string]
        t = t.replace(" ", "");
        if (!t) {
            notification.error({message: "Please fill up the previous option boxes before adding a new one"});
            return;
        }
        if (!actualOptionData.current[options.length - 1].text) {
            notification.info({ message: "Please fill up the previous option boxes before adding a new one" });
            return;
        }
        s = actualOptionData.current[options.length - 1].text;
        t = s.replace(new RegExp('<[^>]*>', 'g'), ''); // this replaces all HTML tag with "" [empty string]
        t = t.replace(" ", "");
        if (!t) {
            notification.error({message: "Please fill up the previous option boxes before adding a new one"});
            return;
        }
        actualOptionData.current[options.length] = { text: "", isCorrect: false };
        updateOptions(prev => [...prev, `_`]);
    }
    
    function toSetCorrectAnswer(list) {
        // list = [<list of items checked>] but in this case my values are index itself so I can directly put them in my checkbox state.
        for (let item of actualOptionData.current) {
            item.isCorrect = false;
        }
        for (let i of list) {
            actualOptionData.current[i].isCorrect = true;
        }
        // @ts-ignore
        updateCheckboxes(() => [...list]);
    }

    function toDeleteOption(id) {
        if (options.length === 2) {
            console.log("Nope");
            notification.error({message: "Can't delete when below three options"});
            return;
        }
        let newOptions = options;
        newOptions.pop();
        actualOptionData.current = actualOptionData.current.filter((_,index) => index != id );
        updateOptions(() => [...newOptions]);
        const positions = actualOptionData.current.map((option, indx) => {
            if (option.isCorrect) {
                return indx;
            }
        }).filter(item => {
            if(item === 0 || item === 1 || item === 2 || item === 3 || item === 4 || item === 5) return true;
        });
        // @ts-ignore
        updateCheckboxes(() => [...positions]);
    }

    return(
        <Checkbox.Group value={checkboxes} onChange={ (list) => {toSetCorrectAnswer(list)} }>
            <div className="options-box">
                {[0,1,2,3,4,5].map((keyId, indx) => {
                    return <div className="radio-wrapper center-flex" key={keyId} style={{display: options[indx]? 'flex' : 'none'}}>
                        <Checkbox style={{marginRight: 8}} value={keyId}></Checkbox>
                        <SimpleEditorOption 
                            defaultValue={indx}
                            placeholder="Write an option.."
                            actualOptionData={actualOptionData}
                            idName={indx}
                            toolbarContainerLoaded={toolbarContainerLoaded}
                            mathJax={mathJax}
                        />
                        <div className="delete-field-btn">
                            <MinusCircleFilled onClick={() => toDeleteOption(keyId)} style={{ fontSize: 18, color: "red" }} />
                        </div>
                    </div>
                })}
                {options.length < 6 && <Button className='align--center' type="primary" onClick={addRadio}>
                        {t('uploadQuestion.moreOptionBtn')}
                </Button>}
            </div>
        </Checkbox.Group>
    )
}

export default OpC;
