import { Button, Empty, Image, Layout, Pagination, Radio, Skeleton, Tooltip, Typography, message } from 'antd';
import React, { useState, useEffect, useRef } from 'react';
import { S3_BUCKET_EXAM_PREFIX } from '../../_services/config';
import { selectorService } from '../../services/selectorService';
import { Link } from 'react-router-dom';
import './ExamModule.css';
import { authenticationService } from '../../_services';
import { PauseOutlined } from '@ant-design/icons';
import empty from '../EmptyImage';

const LiveExamNew = () => {
    const mounted = useRef();
    const userRole = authenticationService.currentUserValue?.role_id;
    const [buttonLoadState, setButtonLoadState] = useState(false);
    const [pageLoading, setPageLoadingState] = useState(true);
    const [pageState, setPageValues] = useState({
        total_count: -1,
        total_pages: -1,
        pageNumber: 1,
        pageSize: 10,
        type: "subject",
    });
    const [pageData, setPageData] = useState([]);

    useEffect(() => {
        mounted.current = true;
        // someFetchingFunctionHere
        if (pageState.type === "subject") {
            fetchSubjectLiveExam();
        }
        return () => {
            // cleanup
            mounted.current = false;
        };
    }, [pageState.pageNumber, pageState.type]);

    async function fetchSubjectLiveExam() {
        if(!pageLoading) {
            setPageLoadingState(true);
        }
        try {
            const res = await selectorService.liveExam(pageState);
            process.env.NODE_ENV === "development" && console.log(res);
            if(+res.status.code < 0) {
                if(res.status.message[0] === "No Record(s) Found!") {
                    mounted.current && setPageValues(prev => ({
                        ...prev,
                        total_count: 0,
                        total_pages: 0,
                    }));
                    mounted.current && setPageData([]);
                    setPageLoadingState(false);
                    return;
                }
                else throw res.status.message[0];
            }
            mounted.current && res && setPageValues(prev => ({
                ...prev,
                total_count: res.result.total_count,
                total_pages: res.result.total_pages,
            }));
            mounted.current && res && setPageData(prev => (
                [...res.result.exams]
            ));
            setPageLoadingState(false);
        } catch (error) {
            console.log(error);
            setPageLoadingState(false);
        }
    }

    const onChangePageNumber = (page) => {
        setPageValues(prev => ({...prev, pageNumber: page}));
    };

    async function onClickPauseButton(id) {
        setButtonLoadState(true);
        try {
            const res = await selectorService.stopPublishedExam(id);
            if(res === 1) {
                message.success("Paused the exam successfully!");
                fetchSubjectLiveExam();
            } else {
                message.error("Couldn't pause the exam, operation failed.");
            }
            setButtonLoadState(false);
        } catch (error) {
            console.log(error);
            if(error === 1) {
                message.success("Paused the exam successfully!");
            } else {
                message.error("Couldn't pause the exam, operation failed.");
            }
            setButtonLoadState(false);
        }
    }

    return (
        <Layout className=''>
            <section className='practice-container exam-container'>
                <div className='practice-type-selector'>
                    <Radio.Group buttonStyle={"solid"} size={"large"}
                        style={{display: 'grid', gridTemplateColumns: '1fr', width: '100%'}} 
                        defaultValue="subject"
                    >
                        <Radio.Button value="subject">Live Exams</Radio.Button>
                    </Radio.Group>
                </div>
                <div className='table-look-up--live'>
                <div className='expired-table-header'>
                        <Typography.Text strong>Image</Typography.Text>
                        <Typography.Text strong>Exam Name</Typography.Text>
                        <Typography.Text strong>Start Date</Typography.Text>
                        <Typography.Text strong>End Date</Typography.Text>
                        <Typography.Text strong>Author</Typography.Text>
                        <Typography.Text strong>Duration</Typography.Text>
                        <Typography.Text strong>Questions</Typography.Text>
                        <Typography.Text strong>Mark</Typography.Text>
                        <Typography.Text strong>Actions</Typography.Text>
                    </div>
                    <div className='live-table-data'>
                    {pageLoading? [0, 1, 2].map((index) => (<div key={index}>
                            <Skeleton.Avatar size={"large"} shape={'square'} active={true} />
                            <Skeleton avatar={false} title={false} paragraph={{rows: 1, width: 120}} active={true} />
                            <Skeleton avatar={false} title={false} paragraph={{rows: 1, width: 80}} active={true} />
                            <Skeleton avatar={false} title={false} paragraph={{rows: 1, width: 50}} active={true} />
                            <Skeleton avatar={false} title={false} paragraph={{rows: 1, width: 50}} active={true} />
                            <Skeleton avatar={false} title={false} paragraph={{rows: 1, width: 50}} active={true} />
                            <Skeleton avatar={false} title={false} paragraph={{rows: 1, width: 20}} active={true} />
                            <Skeleton avatar={false} title={false} paragraph={{rows: 1, width: 20}} active={true} />
                            <span><Skeleton.Button size='small' /> <Skeleton.Button size='small' /></span>
                        </div>))
                        : pageData.length? pageData.map(data => {
                            const startDate = new Date(data.start_date);
                            const endDate = new Date(data.end_date);
                            return <div key={data.id}>
                                <span><Image
                                    src={`${S3_BUCKET_EXAM_PREFIX + data.id}.png`}
                                    fallback={empty()}
                                    width={70}
                                    height={70}
                                    className="DraftExamImage"
                                /></span>
                                <span><Tooltip title={data.name} placement={"topLeft"}>
                                    <Typography.Text ellipsis style={{width: 120}}>{data.name}</Typography.Text>
                                </Tooltip></span>
                                <span>
                                    <p className='mb-0-0'>{startDate.toLocaleDateString()}</p>
                                    <p className='mb-0-0'>{startDate.toLocaleTimeString('hi', { hour12: true })}</p>
                                </span>
                                <span>
                                    <p className='mb-0-0'>{endDate.toLocaleDateString()}</p>
                                    <p className='mb-0-0'>{endDate.toLocaleTimeString('hi', { hour12: true })}</p>
                                </span>
                                <span>{data.author_name}</span>
                                <span>{data.exam_duration/60} miuntes</span>
                                <span>{data.total_questions}</span>
                                <span>{data.total_marks}</span>
                                <span>
                                    {userRole === 3 && <Typography.Text type='secondary' strong>No actions allowed for Teachers</Typography.Text>}
                                    {userRole === 2 && <Tooltip title='Pause'>
                                        <Button onClick={() => onClickPauseButton(data.id)} loading={buttonLoadState} shape={'circle'} icon={<PauseOutlined />} danger /> 
                                    </Tooltip>}
                                    {userRole === 2 && <Button loading={buttonLoadState}>Clone</Button> }
                                    {userRole === 2 && <Button type='primary'>
                                        <Link to={{
                                            pathname: "/associateBatch",
                                            state: {
                                            id: data.id,
                                            // current: step - 1,
                                            start_date: data.start_date,
                                            end_date: data.end_date,
                                            exam_duration: data.exam_duration,
                                            total_questions: data.exam_duration,
                                            total_marks: data.total_marks,
                                            name: data.name,
                                            },
                                        }}>
                                            Edit Associated Batch
                                        </Link>
                                    </Button>}
                                </span>
                            </div>
                        }): <Empty />}
                    </div>
                </div>
            </section>
            <div className="button-container mb-1-0">
                <Pagination defaultCurrent={1} current={pageState.pageNumber} total={pageState.total_count} onChange={onChangePageNumber} />
            </div>
        </Layout>
    );
}

export default LiveExamNew;
