import React, { useRef, useState, useEffect } from 'react';
import { selectorService } from '../../services/selectorService';
import { Card, Layout, Switch, Typography, message } from 'antd';
import { LoadingOutlined } from '@ant-design/icons';
import "./AssociateExam.css";
import { useHistory } from 'react-router-dom';

const AssociateBatchNew = (props) => {
    const history = useHistory();
    const mounted = useRef(true);
    const [aboutExam, setAboutExam] = useState({
        start_date: new Date(),
        end_date: new Date(),
        exam_duration: "",
        total_marks: "",
        total_questions: "",
        name: "",
        id: -1,
    });
    const [pageState, setpageState] = useState({
        loading: true,
        buttonProcessing: false,
    });
    const [associatedBatches, setAssociatedBatches] = useState([]);
    const [sourcePool, setPool] = useState([]);

    useEffect(() => {
        if (props.location && props.location.state && props.location.state.name) {
            setAboutExam(prev => ({
                ...prev,
                start_date: new Date(props.location.state.start_date),
                end_date: new Date(props.location.state.end_date),
                exam_duration: props.location.state.exam_duration,
                total_marks: props.location.state.total_marks,
                total_questions: props.location.state.total_questions,
                name: props.location.state.name,
                id: props.location.state.id,
            }))
            mounted.current = true;
            fetchBatchesForCurrentClass();
            fetchAssociatedBatches();
        } else {
            history.push("/");
        }
        return () => {
            mounted.current = false;
        }
    }, [aboutExam.id]);

    async function fetchBatchesForCurrentClass() {

        try {
            const res = await selectorService.getAllBatch();
            if (+res.status.code < 0) {
                throw res.status.message[0];
            }
            if (mounted.current) {
                setPool(res.result);
                setpageState(prev => ({ ...prev, loading: false }));
            }
        } catch (error) {
            console.log(error);
            message.error("Something went wrong, please reload and try again");
        }
    }

    async function fetchAssociatedBatches() {
        try {
            if(aboutExam.id < 0) {
                return;
            }
            const res = await selectorService.getExamBatch({id: aboutExam.id});
            if (+res.status.code < 0) {
                if(res.status.message[0] === "No Record(s) Found!") return;
                throw res.status.message[0];
            }
            if (mounted.current) {
                setAssociatedBatches(res.result.idList);
                setpageState(prev => ({ ...prev, loading: false }));
            }
        } catch (error) {
            console.log(error);
            message.error("Something went wrong, please reload and try again");
        }
    }

    if (pageState.loading) {
        return <Layout><LoadingOutlined spin /></Layout>
    }

    function computeSwitchValue(id) {
        return associatedBatches.find(item => (item === id));
    }

    async function changeSwitch(value, batchID) {
        setpageState(prev => ({...prev, buttonProcessing: true}));
        try {
            if(value) {
                const res = await selectorService.addBatchToExam({id: aboutExam.id, idList: [batchID]});
                if(+res.status.code < 0) {
                    throw res.status.message[0];
                }
                if (mounted.current) {
                    setAssociatedBatches(prev => ([...prev, batchID]));
                    setpageState(prev => ({...prev, buttonProcessing: false}));
                }
            } else {
                const res = await selectorService.deleteExamBatch({id: aboutExam.id, idList: [batchID]});
                if(+res.status.code < 0) {
                    throw res.status.message[0];
                }
                if(mounted.current) {
                    const array = associatedBatches.filter(item => ( item !== batchID ));
                    setAssociatedBatches(() => (array));
                    setpageState(prev => ({...prev, buttonProcessing: false}));
                }
            }
        } catch (error) {
            console.log(error);
            message.error("Something went wrong, please reload and try again");
            mounted.current && setpageState(prev => ({...prev, buttonProcessing: false}));
        }
    }

    return (
        <Layout prefixCls='associate-exam'>
            <Layout.Content prefixCls='container'>
                <div className='exam-info'>
                    <div className='exam-info-header'>
                        <Typography.Text strong>Exam Name</Typography.Text>
                        <Typography.Text strong>Duration</Typography.Text>
                        <Typography.Text strong>Start Date</Typography.Text>
                        <Typography.Text strong>End Date</Typography.Text>
                    </div>
                    <div className='selected-exam-info'>
                        <Typography.Text strong ellipsis>{aboutExam.name}</Typography.Text>
                        <span>{aboutExam.exam_duration}</span>
                        <span>{aboutExam.start_date.toLocaleDateString()} {aboutExam.start_date.toLocaleTimeString()}</span>
                        <span>{aboutExam.end_date.toLocaleDateString()} {aboutExam.end_date.toLocaleTimeString()}</span>
                    </div>
                </div>
                <Typography.Paragraph type='secondary'>Switch off/on the batches to (de-)associate above exam to them</Typography.Paragraph>
                <div className='batch-pool'>
                    {sourcePool.map((batch, i) => {
                        return <div key={batch.id}>
                            <Card size={"small"} title={<>Batch Name - <Typography.Text strong>{batch.name}</Typography.Text></>}>
                                <Typography.Text>No. of students - {batch.student_count}</Typography.Text>
                                <Typography.Text>
                                    <Switch 
                                        onChange={(e) => changeSwitch(e, batch.id)}
                                        checked={computeSwitchValue(batch.id)? true : false} 
                                        loading={pageState.buttonProcessing} 
                                    />
                                </Typography.Text>
                            </Card>
                        </div>
                    })}
                </div>
            </Layout.Content>
        </Layout>
    );
}

export default AssociateBatchNew;
