// material-ui
import {
    Grid, TextField, Typography
} from '@mui/material';
import MainCard from "../../components/MainCard";
import {useContext, useEffect, useState} from "react";
import axios from "axios";
import {apiPath, getUserData} from "../../auth/utils";
import {
    GET_DIVISION_FROM_SUB_DIVISION,
    GET_EVENT_PATH,
    GET_SEARCH_TEMPLATE_COMBO_PATH,
    GET_SEARCH_TEMPLATE_PATH
} from "../../utils/ApiPathConst";
import * as React from "react";
import LoadingComponent from "../extra-pages/LoadingComponent";
import EventTable from "./EventTable";
import EventSearchForm from "./EventSearchForm";
import Qs from "qs";
import Autocomplete from "@mui/material/Autocomplete";
import {isObjEmpty} from "../../utils/Utils";
import {isOptionEqualToValue, notifyLoadSuccess} from "../../utils/CommonFunction";
import UploadContext from "../../components/UploadProvider";
import {useLocation} from "react-router-dom";
import dayjs from "dayjs";

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

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

const EventSearchPage = () => {
    const location = useLocation();
    const queryParams = new URLSearchParams(location.search);
    const [record,setRecord] = useState([]);
    const [searchCriteria, setSearchCriteria] = useState({});
    const [onReady, setOnReady] = useState(false);
    const [isUpdating, setIsUpdating] = useState(false);
    const [expanded, setExpanded] = React.useState(true);
    const userSubDivisionId = localStorage.getItem('subDivisionId');
    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;
            });
    }

    useEffect(() => {

        getUserDivisionDetail();
    }, []);

    useEffect(() => {
        if(!isObjEmpty(userDivision)){
            getTemplateList();
            getEventList(true);
        }
    }, [userDivision]);

    useEffect(() => {
        if(!isObjEmpty(searchCriteria)){
            getEventList(false);
        }
    }, [searchCriteria]);

    //=====TEMPLATE RELATED START=====//
    const { setIsUploading } = useContext(UploadContext);
    const [selectedTemplate, setSelectedTemplate] = useState(null);
    const [searchTemplateList, setSearchTemplateList] = useState([]);
    const [refTemplateData, setRefTemplateData] = useState(null);

    function getTemplateList(){
        const userData = getUserData();
        axios.get(`${apiPath}${GET_SEARCH_TEMPLATE_COMBO_PATH}`, {
                params: {
                    "module": "Event",
                    "userId": userData.id
                },
            }
        )
            .then((response) => {
                if (response.status === 200) {
                    setSearchTemplateList(response.data.records);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    useEffect(() => {
        if(!isObjEmpty(selectedTemplate)){
            getTemplateDetail();
        }
        else{
            setRefTemplateData(null);
        }
    }, [selectedTemplate]);

    function getTemplateDetail(){
        setIsUploading(true);
        setIsUpdating(true);
        axios.get(`${apiPath}${GET_SEARCH_TEMPLATE_PATH}/${selectedTemplate.id}`)
            .then((response) => {
                if (response.status === 200) {
                    setRefTemplateData(JSON.parse(response.data.data.criteria));
                    setIsUploading(false);
                    notifyLoadSuccess();
                }
            })
            .catch(error => {
                console.log(error);
                setIsUploading(false);
                return false;
            });
    }

    //=====TEMPLATE RELATED END=====//


    function getEventList(isInit){
        const userSubDivision = queryParams.get('userSubDivision');
        const year = queryParams.get('year');
        const temp = {
            fromDate: year === null ? null : dayjs(year+"-01-01").format('YYYY-MM-DD'),
            toDate: year === null ? null : dayjs(year+"-12-31").format('YYYY-MM-DD'),
            divisionIdList: userSubDivision === "true" ? [userDivision.id] : null,
        };
        axios.get(`${apiPath}${GET_EVENT_PATH}`, {
                params: isInit? temp : searchCriteria,
                paramsSerializer: function (params) {
                    return Qs.stringify(params, { arrayFormat: 'repeat' });
                },
            }
        )
            .then((response) => {
                if (response.status === 200) {
                    setRecord(response.data.records);
                    setOnReady(true);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    function applySearch(input) {
        setSearchCriteria(input);
    }

    return (
        <Grid container rowSpacing={3} columnSpacing={2.75} >
            <ThemeProvider theme={LIONER_FORM_THEME}>
                <Grid item xs={12} md={12} lg={12} >
                    <Grid container maxWidth justifyContent="space-between" sx={{mt:-2, width:CARD_MAX_WIDTH}} >
                        <Grid item xs={4} s={4} md={4} lg={4}
                            sx={{ mb: -2.25, display: 'flex', alignItems: 'center'}}>
                            <Typography variant="h5">Search Event</Typography>
                        </Grid>
                        <Grid item xs={8} md={5} lg={5} sx={{mb: -2.25}} >
                            <Grid container justifyContent="flex-end">
                                <Grid item xs={4} s={4} md={4} lg={4}
                                    sx={{ display: 'flex', alignItems: 'center'}}>
                                    <Typography variant="h5">Search Template:</Typography>
                                </Grid>
                                <Grid item xs={7} s={7} md={7} lg={6}>
                                    <Autocomplete
                                        disablePortal
                                        id="search-template-combo"
                                        size="small"
                                        value={selectedTemplate === null ? null : selectedTemplate}
                                        options={searchTemplateList}
                                        onChange={(event, newValue) => {
                                            setSelectedTemplate(newValue);
                                        }}
                                        renderInput={(params) => <TextField {...params} />}
                                        isOptionEqualToValue={isOptionEqualToValue}
                                    />
                                </Grid>
                            </Grid>
                        </Grid>
                    </Grid>
                </Grid>
                <Grid item xs={12} md={12} lg={12}>
                    <EventSearchForm
                        isUpdating={isUpdating}
                        setIsUpdating={setIsUpdating}
                        applySearch={applySearch}
                        refTemplateData={refTemplateData}
                        getTemplateList={getTemplateList}
                        setExpanded={setExpanded}
                        expanded={expanded}
                        userDivision={userDivision}
                    />
                {!onReady? <LoadingComponent/> :
                    // Client Table
                    <Grid item xs={12} md={12} lg={12}>
                        <MainCard elevation={0}
                                content={false}
                                sx={{mt:{lg:-1.5}, width: CARD_MAX_WIDTH}}>
                            <div style={{/*height: expanded? '46vh' : '75vh',*/ width: '100%'}}>
                                <EventTable
                                    recordList={record}
                                    pageSize={10}
                                    expanded={expanded}
                                />
                            </div>
                        </MainCard>
                    </Grid>
                }
                </Grid>
            </ThemeProvider>
        </Grid>
    );
};

export default EventSearchPage;
