// material-ui
import {
    Box,
    Grid, Typography
} from '@mui/material';
import EventForm from "./EventForm";
import {useContext, useEffect, useState} from "react";
import * as React from "react";
import axios from "axios";
import {apiPath} from "../../auth/utils";
import {
    GET_EVENT_APPLICATION_PATH,
    GET_EVENT_PATH,
    GET_REMINDER_BEFORE,
    GET_REMINDER_INTERVAL,
    GET_REMINDER_LIMIT,
    GET_REMINDER_LIMIT_MAX,
    GET_SUB_DIVISION_COMBO_LIST,
} from "../../utils/ApiPathConst";
import LoadingComponent from "../extra-pages/LoadingComponent";
import {useLocation, useParams} from "react-router-dom";
import ApplicationTable from "./ApplicationTable";
import MainCard from "../../components/MainCard";
import AbilityContext from "../../components/AbilityProvider";

import {LIONER_FORM_THEME, CARD_MAX_WIDTH} from "../../themes/themeConst";
import {ThemeProvider} from "@emotion/react";
import {isObjEmpty} from "../../utils/Utils";

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

const EventPanel = () => {
    const params = useParams();
    const ability = useContext(AbilityContext);
    const location = useLocation();
    const queryParams = new URLSearchParams(location.search);
    const refId = queryParams.get("refId");

    const [onReady, setOnReady] = useState(false);
    const [isNewRecord, setIsNewRecord] = useState(false);
    const [applicationDetail, setApplicationDetail] = useState({});
    const [subDivisionCombo, setSubDivisionCombo] = useState([]);
    const [refSubDivisionList, setRefSubDivisionList] = useState([]);
    const [eventDetail, setEventDetail] = useState({});
    const [applicationList, setApplicationList] = useState([]);
    const [reminderInterval, setReminderInterval] = useState(0);
    const [reminderBefore, setReminderBefore] = useState(0);
    const [reminderLimit, setReminderLimit] = useState(0);
    const [reminderLimitMax, setReminderLimitMax] = useState(0);

    //const [tagCombo, setTagCombo] = useState({});

    function updateApplicationDetail(applicationData) {
        setApplicationDetail(applicationData);
    }

    useEffect(() => {
        getReminderInterval();
        getReminderBefore();
        getReminderLimit();
        getReminderLimitMax();
        if(refId !== null){
            setIsNewRecord(true);
            getEventDetail(refId);
        }
        else if(params.id<0){
            setIsNewRecord(true);
        }
        else{
            getEventDetail(params.id);
        }
        getGroupList();
        getApplicationList();
    }, []);

    function getReminderBefore(){
        axios.get(`${apiPath}${GET_REMINDER_BEFORE}`,
        )
            .then((response) => {
                if (response.status === 200) {
                    setReminderBefore(response.data.data);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    function getReminderLimit(){
        axios.get(`${apiPath}${GET_REMINDER_LIMIT}`,
        )
            .then((response) => {
                if (response.status === 200) {
                    setReminderLimit(response.data.data);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    function getReminderLimitMax(){
        axios.get(`${apiPath}${GET_REMINDER_LIMIT_MAX}`,
        )
            .then((response) => {
                if (response.status === 200) {
                    setReminderLimitMax(response.data.data);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    useEffect(() => {
        if (!isObjEmpty(subDivisionCombo)) {
            setOnReady(true);
        }
        else if(isNewRecord &&
                Object.keys(eventDetail).length > 0
        ){
            setOnReady(true);
        }
    }, [subDivisionCombo,eventDetail]);

    function getApplicationList(){
        const byDivision = {
            eventId: params.id,
            userSubDivisionId: ability.can('VIEW', 'ALL_RECORD') ? null : localStorage.getItem('subDivisionId'),
        }
        axios.get(`${apiPath}${GET_EVENT_APPLICATION_PATH}`,
            {
                params: byDivision,
            }
        )
            .then((response) => {
                if (response.status === 200) {
                    setApplicationList(response.data.records);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    function getReminderInterval(){
        axios.get(`${apiPath}${GET_REMINDER_INTERVAL}`,
        )
            .then((response) => {
                if (response.status === 200) {
                    setReminderInterval(response.data.data);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    function getEventDetail(eventId) {
        axios.get(`${apiPath}${GET_EVENT_PATH}/${eventId}`,
        )
            .then((response) => {
                if (response.status === 200) {
                    setEventDetail(response.data.data);
                    setRefSubDivisionList(response.data.eventDivision);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    function getGroupList() {
        axios.get(`${apiPath}${GET_SUB_DIVISION_COMBO_LIST}`,
        )
            .then((response) => {
                if (response.status === 200) {
                    setSubDivisionCombo(response.data.records);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    return (
        !onReady ?
            <LoadingComponent/>
            :
            <Grid container rowSpacing={3} columnSpacing={2.75} >
                <ThemeProvider theme={LIONER_FORM_THEME}>
                <Grid item xs={12} s={12} md={12} lg={12}>
                    <Grid container justifyContent="flex-start" alignItems="center">
                        <Grid item xs={3} sx={{mt:-1, mb: -2.25}} >
                            <Box sx={{ display: 'flex', alignItems: 'center'}}>
                                <Typography align="center" variant="h5" >{isNewRecord? "New Event" : "Maintain Event"}</Typography>
                            </Box>
                        </Grid>
                    </Grid>
                </Grid>

                {/*row 1*/}
                <Grid item xs={12} md={12} lg={12} >
                    <EventForm
                        refReminderInterval={reminderInterval}
                        refReminderBefore={reminderBefore}
                        refReminderLimit={reminderLimit}
                        refReminderLimitMax={reminderLimitMax}
                        applicationList={applicationList}
                        getEventDetail={getEventDetail}
                        refEventDetail={eventDetail}
                        applicationDetail={applicationDetail}
                        updateApplicationDetail={updateApplicationDetail}
                        isNewRecord={isNewRecord}
                        refSubDivisionList={refSubDivisionList}
                    />
                </Grid>

                {/*row 2*/}
                {
                    params.id > 0 ?
                        <Grid item xs={12} md={12} lg={12}>
                            <MainCard
                                sx={{width:CARD_MAX_WIDTH}}
                            >
                                <ThemeProvider theme={LIONER_FORM_THEME}>
                                <ApplicationTable recordList={applicationList}/>
                                </ThemeProvider>
                            </MainCard>
                        </Grid>
                        :
                        undefined
                }
                </ThemeProvider>
            </Grid>

    );
};

export default EventPanel;
