import {useEffect, useState} from 'react';

// material-ui
import {
    Box,
    Grid,
    MenuItem,
    TextField,
    Typography
} from '@mui/material';
import RankingCard from "./RankingCard";
import {cardBorderColor} from "../../themes/colorConst";
import ThreeInOneCard from "./ThreeInOneCard";
import * as React from "react";
import axios from "axios";
import {apiPath} from "../../auth/utils";
import {
    GET_DIVISION_FROM_SUB_DIVISION,
    GET_EVENT_CATEGORY_SUMMARY,
    GET_EVENT_DIVISION_SUMMARY,
    GET_EVENT_TAG_SUMMARY,
    GET_EVENT_TOP6,
    GET_EVENT_YEAR_COMBO
} from "../../utils/ApiPathConst";
import LoadingComponent from "../extra-pages/LoadingComponent";

import {LIONER_FORM_THEME} from "../../themes/themeConst";
import {ThemeProvider} from "@emotion/react";
import {handleLogoutFunction} from "../../auth";
import {useDispatch} from "react-redux";
import {useNavigate} from "react-router-dom";
import {BRANCH_COMBO, DASHBOARD_DIVISION_COMBO} from "../../utils/ComboConst";
// sales report status


// ==============================|| DASHBOARD - DEFAULT ||============================== //

const LIONERDashboard = () => {
    const dispatch = useDispatch()
    const navigate = useNavigate()
    const userSubDivisionId = localStorage.getItem('subDivisionId');

    const [selectedYear, setSelectedYear] = useState(null);
    const [yearList, setYearList] = useState([]);
    const [onReady, setOnReady] = useState(false);
    const [top6List, setTop6List] = useState([]);
    const [divisionSummary, setDivisionSummary] = useState([]);
    const [tagSummary, setTagSummary] = useState([]);
    const [categorySummary, setCategorySummary] = useState([]);
    const [fetchedYear, setFetchedYear] = useState(false);
    const [isUpdating, setIsUpdating] = useState(false);
    const [selectedBranch, setSelectedBranch] = useState(BRANCH_COMBO[0]);
    const [viewDivisionOnly, setViewDivisionOnly] = useState(null);
    const [viewDivisionDisplay, setViewDivisionDisplay] = useState(false);
    const [userDivision, setUserDivision] = useState(null);

    function getUserDivisionDetail(){
        axios.get(`${apiPath}${GET_DIVISION_FROM_SUB_DIVISION}`,{
            params:{
                id: userSubDivisionId
            }
        })
            .then((response) => {
                if (response.status === 200) {
                    setUserDivision(response.data.data);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }
    function getDivisionSummary(){
        if (selectedYear) {
            axios.get(`${apiPath}${GET_EVENT_DIVISION_SUMMARY}`,{
                params:{
                    year: selectedYear,
                    branch: selectedBranch === null ? null : selectedBranch.label,
                    viewDivisionOnly: viewDivisionOnly === null ? false : viewDivisionOnly,
                    userSubDivisionId: userSubDivisionId
                }
            })
                .then((response) => {
                    if (response.status === 200) {
                        setDivisionSummary(response.data.records);
                        setIsUpdating(true);
                    }
                })
                .catch(error => {
                    console.log(error);
                    return false;
                });
        }
    }

    function getTagSummary(){
        axios.get(`${apiPath}${GET_EVENT_TAG_SUMMARY}`,{
            params:{
                year: selectedYear,
                userSubDivisionId: viewDivisionOnly? userSubDivisionId : null
            }
        })
            .then((response) => {
                if (response.status === 200) {
                    setTagSummary(response.data.records);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    function getCategorySummary(){
        axios.get(`${apiPath}${GET_EVENT_CATEGORY_SUMMARY}`,{
            params:{
                year: selectedYear,
                userSubDivisionId: viewDivisionOnly? userSubDivisionId : null
            }
        })
            .then((response) => {
                if (response.status === 200) {
                    setCategorySummary(response.data.records);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    function getYearComboList(){
        axios.get(`${apiPath}${GET_EVENT_YEAR_COMBO}`
        )
            .then((response) => {
                if (response.status === 200) {
                    if(response.data.records.length === 0){
                        let tempList = [{
                            label: new Date().getFullYear(),
                            id: new Date().getFullYear()
                        }];
                        setYearList(tempList);
                        setSelectedYear(tempList[0].label);
                        setFetchedYear(true);
                    }
                    else{
                        setYearList(response.data.records);
                        setSelectedYear(response.data.records[0].label);
                        setFetchedYear(true);
                    }
                }
            })
            .catch(error => {
                dispatch(handleLogoutFunction());
                navigate('/login');
                console.log(error);
                return false;
            });
    }

    function getYearTop6(){

        axios.get(`${apiPath}${GET_EVENT_TOP6}`,{
            params:{
                year: selectedYear,
                userSubDivisionId: viewDivisionOnly? userSubDivisionId : null
            }
        })
            .then((response) => {
                if (response.status === 200) {
                    setTop6List(response.data.records);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    useEffect(() => {
        getYearComboList();
        getUserDivisionDetail();
        setViewDivisionDisplay(1);
    }, []);

    useEffect(() => {
        if(fetchedYear){
            if(selectedYear!== null){
                getYearTop6();
                getDivisionSummary();
                getTagSummary();
                getCategorySummary();
            }
            setOnReady(true);
        }

    }, [fetchedYear, selectedYear, viewDivisionOnly]);

    useEffect(() => {
        getDivisionSummary();
    }, [selectedBranch]);

    return (
        !onReady ?
            <LoadingComponent/>
            :
        <Grid container direction="row">
            <Grid item xs={12} md={12} lg={12} sx={{mt:{xs:0, s:2, md:2, lg:0}}}>
                <Grid container alignItems="stretch" /*justifyContent="space-between"*/>
                    <Grid item xs={12} md={12} lg={12}>
                        <Typography align="left" variant="h3" >Welcome to LIONER System</Typography>

                    </Grid>
                </Grid>
            </Grid>
        </Grid>
    );
};

export default LIONERDashboard;
