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

const LivePracticeNew = () => {
    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: "topic",
    });
    const [pageData, setPageData] = useState([]);

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

    const onChangePracticeType = (e) => {
        setPageValues(prev => ({ ...prev, type: e.target.value, pageNumber: 1 }));
    };

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

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

    async function onClickPauseButton(id) {
        // Pause is only implemented for EXAM, but not PRACTICE.
        setButtonLoadState(true);
        try {
            const res = await selectorService.stopPublishedExam(id);
            if(res === 1) {
                message.success("Paused the exam successfully!");
                pageState.type === "topic"? fetchTopicLivePractice() : fetchSubjectLivePractice();
            } 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);
        }
    }

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

    return (
        <Layout className=''>
            <section className='practice-container'>
                <div className='practice-type-selector'>
                    <Radio.Group buttonStyle={"solid"} size={"large"}
                        style={{display: 'grid', gridTemplateColumns: '1fr 1fr', width: '100%'}} 
                        onChange={onChangePracticeType} defaultValue="topic"
                    >
                        <Radio.Button value="subject">Subject based Practices</Radio.Button>
                        <Radio.Button value="topic">Topic based Practices</Radio.Button>
                    </Radio.Group>
                </div>
                <div className='table-look-up--live'>
                    <div className='live-table-header'>
                        <Typography.Text strong>Image</Typography.Text>
                        <Typography.Text strong>Exam Name</Typography.Text>
                        <Typography.Text strong>Last updated</Typography.Text>
                        <Typography.Text strong>Author</Typography.Text>
                        <Typography.Text strong>Total Questions</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: 110}} 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} />
                            <span><Skeleton.Button size='small' /> <Skeleton.Button size='small' /></span>
                        </div>))
                        : pageData.length? pageData.map(data => {
                            const createdDate = new Date(data.created_on);
                            const updatedDate = new Date(data.updated_on);
                            return <div key={data.id}>
                                <span><Image
                                    src={`${S3_BUCKET_PRACTICE_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>{createdDate.toLocaleDateString()} {createdDate.toLocaleTimeString('hi', { hour12: false })}</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.total_questions}</span>
                                <span>
                                    <Button type='primary'>View Report</Button>
                                    {userRole === 2 && <Button type='primary'>
                                        <Link to={{
                                                pathname: "/associatePracticeBatch",
                                                state: {
                                                    id: data.id,
                                                    current: 2,
                                                    start_date: data.start_date,
                                                    total_questions: data.total_questions,
                                                    name: data.name,
                                                    author_name: data.author_name,
                                                },
                                        }}>
                                            Associate Batch
                                        </Link>
                                    </Button>}
                                </span>
                            </div>
                        }): <Empty />}
                    </div>
                </div>
            </section>
            <div className="button-container">
                <Pagination defaultCurrent={1} current={pageState.pageNumber} total={pageState.total_count} onChange={onChangePageNumber} />
            </div>
        </Layout>
    );
}

export default LivePracticeNew;
