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

const DraftExamNew = () => {
    const mounted = useRef();
    const [buttonState, setButtonState] = useState(true);
    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") {
            fetchSubjectDraftExam();
        }
        return () => {
            // cleanup
            mounted.current = false;
        };
    }, [pageState.pageNumber, pageState.type]);

    async function fetchSubjectDraftExam() {
        if (!pageLoading) {
            setPageLoadingState(true);
        }
        try {
            const res = await selectorService.draftExam(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);
                    setButtonState(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]
            ));
            setButtonState(false);
            setPageLoadingState(false);
        } catch (error) {
            console.log(error);
            setButtonState(false);
            setPageLoadingState(false);
        }
    }

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

    function onClickDeleteButton(id) {
        setButtonState(true);
        selectorService.deleteExam(id).then((res) => {
            if (+res.status.code < 0)
                throw res.status.message[0];
            else {
                setPageLoadingState(true);
                if (pageState.type === "subject") {
                    fetchSubjectDraftExam();
                }
                message.success("Deleted Successfully");
            }
        })
        .catch((err) => {
            process.env.NODE_ENV === "development" && console.log(err);
            message.error("Some error occured");
            setButtonState(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">Draft Exams</Radio.Button>
                    </Radio.Group>
                </div>
                <div className='table-look-up--draft'>
                    <div className='draft-table-header'>
                        <Typography.Text strong>Image</Typography.Text>
                        <Typography.Text strong>Exam Name</Typography.Text>
                        <Typography.Text strong>Created</Typography.Text>
                        <Typography.Text strong>Last updated</Typography.Text>
                        <Typography.Text strong>Author</Typography.Text>
                        <Typography.Text strong>Section Count</Typography.Text>
                        <Typography.Text strong>Actions</Typography.Text>
                    </div>
                    <div className='draft-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: 80 }} active={true} />
                            <Skeleton avatar={false} title={false} paragraph={{ rows: 1, width: 60 }} 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 > 0? pageData.map(data => {
                            let step = 2;
                            if (data.sections_count >= 1) step = 3;
                            if (data.sections_status !== "DRAFT") step = 4;
                            const createdDate = new Date(data.created_on);
                            const updatedDate = new Date(data.updated_on);
                            return <div key={data.id}>
                                <span><Image
                                    src={`${S3_BUCKET_EXAM_PREFIX + data.id}.png`}
                                    fallback={EmptyImage()}
                                    width={70}
                                    height={70}
                                    className="DraftExamImage"
                                /></span>
                                <span><Tooltip title={data.name}>
                                    <Typography.Text ellipsis style={{ width: 120 }}>{data.name}</Typography.Text>
                                </Tooltip></span>
                                <span>
                                    <p className='mb-0-0'>{createdDate.toLocaleDateString()}</p>
                                    <p className='mb-0-0'>{createdDate.toLocaleTimeString('hi', { hour12: true })}</p>
                                </span>
                                <span>
                                    <p className='mb-0-0'>{updatedDate.toLocaleDateString()}</p>
                                    <p className='mb-0-0'>{updatedDate.toLocaleTimeString('hi', { hour12: true })}</p>
                                </span>
                                <span>{data.author_name}</span>
                                <span>{data.sections_count}</span>
                                <span>
                                    <Button loading={buttonState}>
                                        <Link to={{
                                            pathname: "/createExam",
                                            state: { id: data.id, current: (step - 1) },
                                        }}>
                                            Edit
                                        </Link>
                                    </Button>
                                    <Button loading={buttonState} danger onClick={() => onClickDeleteButton(data.id)}>Delete</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 DraftExamNew;
