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 "../Exams/AssociateExam.css";
import { useHistory } from 'react-router-dom';

const PracticeAssociateBatchv2 = (props) => {
    const history = useHistory();
    const mounted = useRef(true);
    const [aboutPractice, setAboutPractice] = useState({
        start_date: new Date(),
        end_date: new Date(),
        exam_duration: "",
        total_marks: "",
        total_questions: "",
        name: "",
        id: -1,
        author_name: ""
    });
    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) {
            setAboutPractice(prev => ({
                ...prev,
                start_date: new Date(props.location.state.start_date),
                total_marks: props.location.state.total_marks,
                total_questions: props.location.state.total_questions,
                name: props.location.state.name,
                id: props.location.state.id,
                author_name: props.location.state.author_name
            }))
            mounted.current = true;
            fetchBatchesForCurrentClass();
            fetchAssociatedBatches();
        } else {
            history.push("/");
        }
        return () => {
            mounted.current = false;
        }
    }, [aboutPractice.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 {
            // throw "API not implemented. Not able to get practice batches";
            if(aboutPractice.id < 0) {
                return;
            }
            const res = await selectorService.getPracticeBatch({id: aboutPractice.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(error);
        }
    }

    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 {
            // throw "API not implemented properly";
            if(value) {
                const res = await selectorService.addBatchToPractice({id: aboutPractice.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.detachBatchFromPractice({id: aboutPractice.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(error);
            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>Start Date</Typography.Text>
                        <Typography.Text strong>Total Questions</Typography.Text>
                        <Typography.Text strong>Author</Typography.Text>
                    </div>
                    <div className='selected-exam-info'>
                        <Typography.Text strong ellipsis>{aboutPractice.name}</Typography.Text>
                        <span>{aboutPractice.start_date.toLocaleDateString()} {aboutPractice.start_date.toLocaleTimeString()}</span>
                        <span>{aboutPractice.total_questions}</span>
                        <span>{aboutPractice.author_name}</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 PracticeAssociateBatchv2;
