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

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

    const {t} = useTranslation();

    const [options, updateOptions] = useState(["_", "_"]);
    const [radio, setRadio] = useState();

    React.useEffect(() => {
        // console.log(actualOptionData.current);
        for(let i = 2; i < actualOptionData.current.length; i++) {
            updateOptions(prev => [...prev, "_"]);
        }
        const position = actualOptionData.current.findIndex((option) => {
            if (option.isCorrect === true) {
                return true;
            }
        });
        setRadio(position);
        return () => {
            actualOptionData.current = [{text: "", isCorrect: false}, {text: "", isCorrect: false}];
        }
    }, []);

    React.useEffect(() => {
        if(!toolbarContainerLoaded) {
            updateOptions(["_","_"]);
            setRadio(-1);
        }
    }, [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(id) {
        // {target: {value}} actually passes the value of radio that gets selected in UI
        // which is then split to extract the option number and then passed into this function as 'id'
        // we then set the correct answer inside 'actualOptionData' reference.
        actualOptionData.current = actualOptionData.current.map((item, index) => {
            if (index === (id)) {
                setRadio(id);
                return {...item, isCorrect: true}
            }
            else return {...item, isCorrect: false};
        });
    }

    function toDeleteOption(id) {
        if (options.length === 2) {
            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]);
        // change setRadio to new position
        const position = actualOptionData.current.findIndex((option) => {
            if (option.isCorrect === true) {
                return true;
            }
        });
        setRadio(position);
    }

    return(
        <Radio.Group value={radio} onChange={ ({ target: { value } }) => { toSetCorrectAnswer(value) } }>
            <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'}}>
                        <Radio style={{marginRight: 8}} value={keyId}></Radio>
                        <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>
        </Radio.Group>
    )
}

export default OpR;
