import React, { useState } from 'react';
import { Typography, Input, Button, Space, Select } from 'antd';
import { EditOutlined } from '@ant-design/icons';
import { useMemo } from 'react';

const errorStyle = {
    border: '#ff00002c 1px solid',
    backgroundColor: '#ff00001c'
}

const EditUploadedQuestion = ({record, index, setData, expandedRows}) => {
    const [disabled, setDisabled] = useState(true);
    const [state, setState] = useState({});

    const options = useMemo(() => ([
        {
            value: '1',
            label: 'A',
            disabled: state.options && !(1 <= state.options.length)
        },
        {
            value: '2',
            label: 'B',
            disabled: state.options && !(2 <= state.options.length)
        },
        {
            value: '3',
            label: 'C',
            disabled: state.options && !(3 <= state.options.length)
        },
        {
            value: '4',
            label: 'D',
            disabled: state.options && !(4 <= state.options.length)
        },
        {
            value: '5',
            label: 'E',
            disabled: state.options && !(5 <= state.options.length)
        },
        {
            value: '6',
            label: 'F',
            disabled: state.options && !(6 <= state.options.length)
        },
    ]), [state.options]);

    React.useEffect(() => {
        setState({...record});
    }, [record, record.length]);

    const handleChange = (e) => {
        const { name, value } = e.target;
        const regex = new RegExp(/^[0-9]+/);

        if (name[0] === 'q' && name[1] === 'u' && regex.test(name[name.length - 1])) {
            setState((prev) => {
                prev.question = value;
                return {...prev};
            }); 
        }

        if (name[0] === 'q' && regex.test(name[1]) && regex.test(name[name.length - 1])) {
            const op = parseInt(name[name.length - 1], 10) - 1;
            setState((prev) => {
                prev.options[op].text = value;
                return {...prev};
            });
        }
    }

    function handleData() {
        if(!disabled) {
            // this switches all options' isCorrect to false
            setState((prev) => {
                prev.options = prev.options.map(option => {
                    option.isCorrect = false;
                    return option;
                });
                return {...prev};
            });
            // this checks for question type (mcq and mrq) and accordingly set some option in isCorrect to true.
            if(state.type !== "TNF") {
                setData((prev) => {
                    prev[index] = state;
                    let ansArr = prev[index].answer;
                    for(let i of ansArr) {
                        if(parseInt(i,10)) {
                            prev[index].options[i-1].isCorrect = true;
                        }
                    }
                    return [...prev];
                });
            }
            // this check if question is tnf and accordingly set the correct option to true.
            if(state.type === "TNF") {
                setData((prev) => {
                    prev[index] = state;
                    let ansArr = prev[index].answer;
                    ansArr === "true" ? prev[index].options[0].isCorrect = true 
                        : prev[index].options[1].isCorrect = true;
                    return [...prev];
                });
            }
        }
        setDisabled(!disabled);
    }

    function handleCancel() {
        if(!disabled) {
            setState({...record});
            setDisabled(!disabled);
        }
    }

    return (
        <form className="question-block">
            <Space direction='vertical' style={{display: "flex"}}>
                <Typography.Title level={5}>Edit Question Number {index + 1}:</Typography.Title>
                <Input.TextArea
                    className="question" type="text" name={'question' + index} value={state.question} onChange={handleChange} disabled={disabled}
                />

                <Typography.Title level={5}>Edit Options:</Typography.Title>
                {state.type === "MCQ" || state.type === "MRQ"? <div className='option-block'>
                    <Input prefix={<Typography.Text style={{borderRight: 'solid 1px black', paddingRight: 8, marginRight: 6}}>A</Typography.Text>} 
                        style={{display: state.options[0]? 'inline-flex': 'none'}}
                        type="text" name={'q' + index + 'option1'} value={state.options[0]?.text} onChange={handleChange} disabled={disabled}
                    />
                    <Input prefix={<Typography.Text style={{borderRight: 'solid 1px black', paddingRight: 8, marginRight: 6}}>B</Typography.Text>} 
                        style={{display: state.options[1]? 'inline-flex': 'none'}}
                        type="text" name={'q' + index + 'option2'} value={state.options[1]?.text} onChange={handleChange} disabled={disabled}
                    />
                    <Input prefix={<Typography.Text style={{borderRight: 'solid 1px black', paddingRight: 8, marginRight: 6}}>C</Typography.Text>} 
                        style={{display: state.options[2]? 'inline-flex': 'none'}}
                        type="text" name={'q' + index + 'option3'} value={state.options[2]?.text} onChange={handleChange} disabled={disabled}
                    />
                    <Input prefix={<Typography.Text style={{borderRight: 'solid 1px black', paddingRight: 8, marginRight: 6}}>D</Typography.Text>} 
                        style={{display: state.options[3]? 'inline-flex': 'none'}}
                        type="text" name={'q' + index + 'option4'} value={state.options[3]?.text} onChange={handleChange} disabled={disabled}
                    />
                    <Input prefix={<Typography.Text style={{borderRight: 'solid 1px black', paddingRight: 8, marginRight: 6}}>E</Typography.Text>} 
                        style={{display: state.options[4]? 'inline-flex': 'none'}}
                        type="text" name={'q' + index + 'option5'} value={state.options[4]?.text} onChange={handleChange} disabled={disabled}
                    />
                    <Input prefix={<Typography.Text style={{borderRight: 'solid 1px black', paddingRight: 8, marginRight: 6}}>F</Typography.Text>} 
                        style={{display: state.options[5]? 'inline-flex': 'none'}}
                        type="text" name={'q' + index + 'option6'} value={state.options[5]?.text} onChange={handleChange} disabled={disabled}
                    />
                </div>:<div className='option-block'>
                    <div style={{gridArea: "span 2"}}><Typography.Text>These options will not change because its a True and False Question</Typography.Text></div>
                    <Input prefix={<Typography.Text style={{borderRight: 'solid 1px black', paddingRight: 8, marginRight: 6}}>A</Typography.Text>} 
                            // style={{display: state.options[0]? 'inline-flex': 'none'}}
                            type="text" name={'q' + index + 'option1'} value={"True"} disabled={disabled}
                    />
                    <Input prefix={<Typography.Text style={{borderRight: 'solid 1px black', paddingRight: 8, marginRight: 6}}>B</Typography.Text>} 
                            // style={{display: state.option1? 'inline-flex': 'none'}}
                            type="text" name={'q' + index + 'option1'} value={"False"} disabled={disabled}
                    />
                </div>}

                <div className='answer-block'>
                    <Typography.Title level={5}>Answer: </Typography.Title>
                    {state.type === "MCQ"? <Select
                        className='answer-dropdown-select'
                        style={state.answer && state.answer.length < 1 ? { width: 240, ...errorStyle } : {width: 240}}
                        // mode={state.type === "MRQ"? "multiple": undefined}
                        value={ state.answer||undefined }
                        placeholder="Select a correct option here"
                        onChange={(e) => setState(prev => {
                            prev.answer = [e]; return {...prev}
                        })}
                        allowClear
                        disabled={disabled}
                        options={options}
                    />: null}
                    {state.type === "MRQ"? <Select
                        className='answer-dropdown-select'
                        style={state.answer && state.answer.length < 1 ? { width: 240, ...errorStyle } : {width: 240}}
                        mode='multiple'
                        value={ state.answer? [...state.answer] : undefined }
                        placeholder={"Select multiple correct answer from the dropdown"}
                        onChange={(e) => setState(prev => { 
                            prev.answer = [...e]; return {...prev}
                        })}
                        allowClear disabled={disabled}
                        options={options}
                    />: null}
                    {state.type === "TNF"? <Select
                        className='answer-dropdown-select'
                        style={state.answer && state.answer.length < 1 ? { width: 240, ...errorStyle } : {width: 240}}
                        value={ state.answer||undefined }
                        placeholder="Select a correct option here"
                        onChange={(e) => setState(prev => {
                            prev.answer = [e]; return {...prev}
                        })}
                        allowClear
                        disabled={disabled}
                        options={[{value: "true", label: "A"}, {value: "false", label: "B"}]}
                    />: null}

                    {/* {state.type !== "TNF" && state.options.length < 1 && <div>Please check if your CSV file has all the data entered correctly before uploading.</div>} */}
                </div>

                <div className='explanation-block'>
                    <Typography.Title level={5}>Explanation: </Typography.Title>
                    <Input.TextArea onChange={(e) => setState(prev => {prev.explanation = e.target.value; return {...prev}})} placeholder="This space is for explanation to the answer"
                        className="explanation" type="text" name={'question' + index + 'explain'} value={state.explanation||undefined} disabled={disabled}
                    />
                </div>
                <div className='button-paradise'>
                    <Button type='primary' ghost icon={<EditOutlined />} onClick={(e) => { e.preventDefault(); handleData();}}>
                        {disabled ? "Edit" : "Save"}
                    </Button>
                    <Button style={{display: disabled? 'none' : 'inline-block', marginInline: 8 }} type={"default"} danger onClick={(e) => { e.preventDefault(); handleCancel();}}>
                        Cancel
                    </Button>
                </div>
            </Space>
        </form>
    );
}

export default EditUploadedQuestion;
