import {Box, Button, Grid, TextField, Typography} from "@mui/material";
import {LIONER_LONG_BUTTON_THEME} from "../../themes/colorConst";
import {useContext, useEffect, useState} from "react";
import MainCard from "../../components/MainCard";
import {cardBorderColor} from "../../themes/colorConst";
import * as React from "react";
import {getListByFieldName} from "../../utils/CommonFunction";
import RankingPieChart from "./RankingPieChart";
import LoadingComponent from "../extra-pages/LoadingComponent";
import axios from "axios";
import {apiPath} from "../../auth/utils";
import {GET_EVENT_SUMMARY_EXCEL} from "../../utils/ApiPathConst";
import {ThemeProvider} from "@emotion/react";
import UploadContext from "../../components/UploadProvider";
import {BRANCH_COMBO} from "../../utils/ComboConst";
import Autocomplete from "@mui/material/Autocomplete";

const ThreeInOneCard = ({
                            setIsUpdating,
                            isUpdating,
                            selectedYear,
                            divisionData,
                            tagData,
                            categoryData,
                            selectedBranch,
                            setSelectedBranch,
                            viewDivisionOnly
                                       }) => {

    const [onReady, setOnReady] = useState(false);
    const { setIsUploading } = useContext(UploadContext);

    const [divisionChartData, setDivisionChartData] = useState([]);
    const [divisionCategoryType, setDivisionCategoryType] = useState([]);

    const [tagChartData, setTagChartData] = useState([]);
    const [tagCategoryType, setTagCategoryType] = useState([]);

    const [categoryChartData, setCategoryChartData] = useState([]);
    const [categoryCategoryType, setCategoryCategoryType] = useState([]);


    const downloadReport = () => {
        const userSubDivisionId = localStorage.getItem('subDivisionId');

        setIsUploading(true);
        axios.get(`${apiPath}${GET_EVENT_SUMMARY_EXCEL}`,{
            responseType: 'blob',
            params:{
                year: selectedYear,
                branch: selectedBranch === null ? null : selectedBranch.label,
                viewDivisionOnly: viewDivisionOnly === null ? false : viewDivisionOnly,
                userSubDivisionId: userSubDivisionId
            }
        })
            .then((response) => {
                if (response.status === 200) {
                    setIsUploading(false);
                    const url = URL.createObjectURL(new Blob([response.data]));
                    const link = document.createElement("a");
                    link.href = url;
                    link.setAttribute("download", "Award_summary_"+ Date.now() + ".xlsx");
                    link.click();
                }
            })
            .catch(error => {
                setIsUploading(false);
                console.log(error);
                return false;
            });
    };

    useEffect(() => {
        if(divisionData.length > 0){
            if(divisionData.length === 1){
                let tempList = divisionData;
                tempList.push({
                    awardCount:0,
                    name:"",
                    rank:2,
                });

                setDivisionChartData([{
                    name: 'Award Count',
                    data: getListByFieldName(tempList, 'awardCount')
                }])
                setDivisionCategoryType(getListByFieldName(tempList,'name'));
            }
            else{
                setDivisionChartData([{
                    name: 'Award Count',
                    data: getListByFieldName(divisionData, 'awardCount')
                }])
                setDivisionCategoryType(getListByFieldName(divisionData,'name'));
            }
        }
    }, [divisionData]);

    useEffect(() => {
        if(divisionChartData.length > 0 && divisionCategoryType.length > 0){
            if(divisionChartData[0].data.length === divisionCategoryType.length){
                setIsUpdating(false);
            }
        }
        else{
            setIsUpdating(false);
        }
    }, [tagData,divisionCategoryType]);

    useEffect(() => {
        setTagChartData(getListByFieldName(tagData, 'awardCount'))
        setTagCategoryType(getListByFieldName(tagData,'name'));
    }, [tagData]);

    useEffect(() => {
        setCategoryChartData(getListByFieldName(categoryData, 'awardCount'));
        setCategoryCategoryType(getListByFieldName(categoryData,'name'));
    }, [categoryData]);

    useEffect(() => {
        /*if(
            divisionChartData.length >0 &&
            tagChartData.length >0 &&
            categoryData.length >0
        ){
        }*/
        setOnReady(true);

    }, [divisionChartData,tagChartData,categoryChartData]);

    return (
        !isUpdating && !onReady ?
            <LoadingComponent/>
            :
        <Grid item xs={12} md={12} lg={12} alignItems="stretch" sx={{height: "86vh", width:"100%", display: "flex"}}>
            <Grid container>
                <Grid item xs={12} md={12} xl={11.5} sx={{ml: {lg:1}, mr:{lg:1}, mb:{lg:-4}}}>
                    <MainCard sx={{backgroundColor: '#fbfff0', height:{lg:'40vh'}}}
                              border={false}
                              title={`Award Summary`}
                              titleClass="rank-card-no-wave rank-card-no-wave-green"
                              boxShadow={3}
                              style={{border: `4px solid ${cardBorderColor[1]} `}}
                    >
                        <Grid container justifyContent="space-between" alignItems="end">
                            <Grid item xs={7} s={7} md={7} >
                                {
                                    viewDivisionOnly ?
                                        undefined
                                        :
                                        <Grid container sx={{mt:-2}}>
                                            <Grid item xs={2} s={1.5} md={1.5} lg={1.5}
                                                  sx={{ml: 3, mr: 3,mt:1, display: 'flex', alignItems: 'flex-start'}}>
                                                <Typography variant="lionerSize" component="span">
                                                    Branch:
                                                </Typography>
                                            </Grid>

                                            <Grid item xs={8} s={8} md={8} lg={6}>
                                                <Autocomplete
                                                    id="module-combo"
                                                    size="small"
                                                    disableClearable={true}
                                                    value={selectedBranch === null ? null : selectedBranch}
                                                    options={BRANCH_COMBO}
                                                    onChange={(event, newValue) => {
                                                        setSelectedBranch(newValue);
                                                    }}
                                                    renderInput={(params) =>
                                                        <TextField
                                                            {...params}
                                                            style={{ zIndex: 3, backgroundColor: '#fafafb' }}
                                                            InputProps={{
                                                                ...params.InputProps,
                                                                readOnly: true
                                                            }}
                                                        />
                                                    }
                                                />
                                            </Grid>
                                        </Grid>
                                }

                            </Grid>

                            <Grid item xs={4} s={4} md={3.5} lg={3.5} sx={{mt:-2}}>
                                <ThemeProvider theme={LIONER_LONG_BUTTON_THEME}>
                                <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: "end"}}>
                                    <Button
                                        // size="medium"
                                        variant="contained"
                                        color="exportExcel"
                                        style={{ zIndex: '3' }}
                                        onClick={downloadReport}
                                        >
                                        Export summary
                                    </Button>
                                </Box>
                                </ThemeProvider>
                            </Grid>
                        </Grid>
                    </MainCard>
                </Grid>

                <Grid item xs={12} md={12} xl={12}>
                    <Grid container>

                        <Grid item xs={12} md={12} l={5.7} xl={5.65} sx={{mt:1, ml: {lg:1}, mr:{lg:1}}}>
                            <MainCard sx={{backgroundColor: '#fbfff0', height:{lg:'40.5vh'}}} style={{border: `4px solid ${cardBorderColor[2]} `}}
                                      border={false}                                      
                                      title={`Awards Summary of Tag`}
                                      titleClass="rank-card-no-wave rank-card-no-wave-blue"
                                      boxShadow={3}                                      
                            >
                                <Grid item xl={12} xs={12} md={12}>
                                    <RankingPieChart
                                        legendPosition='bottom'
                                        chartType='pie'
                                        chartData={tagChartData}
                                        categoryType={tagCategoryType}
                                    />
                                </Grid>
                            </MainCard>
                        </Grid>

                        <Grid item xs={12} md={12} l={5.7} xl={5.65} sx={{mt:1, ml: {lg:1}, mr:{lg:1}}}>
                            <MainCard sx={{ backgroundColor: '#fbfff0', height:{lg:'40.5vh'}}} style={{border: `4px solid ${cardBorderColor[3]} `}}
                                      border={false}
                                      title={`Awards Summary of Category`}
                                      titleClass="rank-card-no-wave rank-card-no-wave-red"
                                      boxShadow={3}
                            >
                                <Grid item xl={12} xs={12} md={12}>
                                    <RankingPieChart
                                        legendPosition='bottom'
                                        chartType='donut'
                                        chartData={categoryChartData}
                                        categoryType={categoryCategoryType}
                                    />
                                </Grid>
                            </MainCard>


                        </Grid>
                    </Grid>
                </Grid>
            </Grid>
        </Grid>


    );
}

export default ThreeInOneCard;
