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 { Link } from 'react-router-dom';
import empty from '../EmptyImage';

const DraftPracticeNew = () => {
    const mounted = useRef();
    const [buttonsLoadState, setButtonsLoadState] = 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") {
            fetchSubjectDraftPractice();
        }
        if (pageState.type === "topic") {
            fetchTopicDraftPractice();
        }
        return () => {
            // cleanup
            mounted.current = false;
        };
    }, [pageState.pageNumber, pageState.type]);

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

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

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

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

    function onClickDeleteButton(id) {
        setButtonsLoadState(true);
        selectorService.deletePractice(id).then((res) => {
                // console.log(res);
                if (+res.status.code < 0)
                    throw res.status.message[0];
                else {
                    setPageLoadingState(true);
                    if (pageState.type === "subject") {
                        fetchSubjectDraftPractice();
                    }
                    if (pageState.type === "topic") {
                        fetchTopicDraftPractice();
                    }
                    message.success("Deleted Successfully");
                }
            })
            .catch((err) => {
                process.env.NODE_ENV === "development" && console.log(err);
                message.error("Some error occured");
                setButtonsLoadState(false);
            });
    }

    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="subject"
                    >
                        <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--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>Total Questions</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: 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 > 0? 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}>
                                    <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.total_questions}</span>
                                <span>
                                    <Button>
                                        <Link
                                            to={{
                                                pathname: "/createPractise",
                                                state: { id: data.id, current: 1 },
                                            }}
                                            >
                                            Edit
                                        </Link>
                                    </Button>
                                    <Button danger onClick={() => onClickDeleteButton(data.id)}>Delete</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 DraftPracticeNew;