// material-ui
import {
    Button,
    Typography,
    Grid, TextField, InputLabel, CardActions
} from '@mui/material';
import MainCard from "../../components/MainCard";
import {useForm} from "react-hook-form";

import {useContext, useEffect, useState} from "react";
import Autocomplete from '@mui/material/Autocomplete';
import * as React from "react";
import axios from "axios";
import {apiPath, getUserData} from "../../auth/utils";
import {
    GET_DIVISION_COMBO_LIST, GET_EVENT_EXPORT,
    GET_SUB_DIVISION_COMBO_LIST, POST_SEARCH_TEMPLATE_PATH, VALIDATE_TEMPLATE_NAME_PATH,
} from "../../utils/ApiPathConst";
import {LIONER_BUTTON_THEME, LIONER_LONG_BUTTON_THEME} from "../../themes/colorConst";
import {
    GeneralCreateTemplateWindow,
    getComboValueByIdList, getComboValueByLabel,
    getIdList, isOptionEqualToValue, notifySaveSuccess,
} from "../../utils/CommonFunction";
import Qs from 'qs';
import {useNavigate} from "react-router";
import {ThemeProvider} from "@emotion/react";
import UploadContext from "../../components/UploadProvider";
import {EVENT_REGION_COMBO, EVENT_TYPE_COMBO} from "../../utils/ComboConst";
import {LocalizationProvider} from "@mui/x-date-pickers/LocalizationProvider";
import {AdapterDayjs} from "@mui/x-date-pickers/AdapterDayjs";
import {DemoItem} from "@mui/x-date-pickers/internals/demo";
import {DatePicker} from "@mui/x-date-pickers/DatePicker";
import dayjs from "dayjs";
import {isObjEmpty} from "../../utils/Utils";
import {useLocation} from "react-router-dom";
import AbilityContext from "../../components/AbilityProvider";
import {LIONER_FORM_THEME, CARD_MAX_WIDTH} from "../../themes/themeConst";
import Collapse from '@mui/material/Collapse';
import {ExpandMore} from "@mui/icons-material";
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';

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

const EventSearchForm = ({applySearch, refTemplateData, isUpdating,
                             setIsUpdating, getTemplateList,setExpanded,expanded,userDivision}) => {

    const navigate = useNavigate()
    const location = useLocation();
    const queryParams = new URLSearchParams(location.search);
    const { setIsUploading } = useContext(UploadContext);
    const ability = useContext(AbilityContext);


    const [selectedRegion, setSelectedRegion] = useState(null);
    const [selectedType, setSelectedType] = useState(null);
    const [selectedSubDivisions, setSelectedSubDivisions] = useState([]);
    const [selectedDivisions, setSelectedDivisions] = useState([]);
    const [fromDate, setFromDate] = useState(null);
    const [toDate, setToDate] = useState(null);

    const [subDivisionList, setSubDivisionList] = useState([]);
    const [divisionList, setDivisionList] = useState([]);

    const { setValue, reset, register, handleSubmit, getValues } = useForm()
    const handleExpandClick = () => {
        setExpanded(!expanded);
    };

    const [fromError, setFromError] = React.useState(null);
    const [toError, setToError] = React.useState(null);

    const fromErrorMessage = React.useMemo(() => {
        switch (fromError) {
            case 'invalidDate': {
                return "Invalid date";
            }
        }
    }, [fromError]);

    const toErrorMessage = React.useMemo(() => {
        switch (toError) {
            case 'invalidDate': {
                return "Invalid date";
            }
        }
    }, [toError]);


    //=====TEMPLATE RELATED START=====//
    const [refEvent, setRefEvent] = useState(null);

    useEffect(() => {
        setRefEvent(refTemplateData);
    }, [refTemplateData]);

    useEffect(() => {
        setRefEvent(refTemplateData);
    }, [subDivisionList]);

    useEffect(() => {
        if(!isObjEmpty(refEvent)){
            setValue('eventName', refEvent.eventName );
            setValue('description', refEvent.description );
            setValue('organization', refEvent.organization );
            setSelectedRegion(getComboValueByLabel(EVENT_REGION_COMBO,refEvent.selectedRegion));
            setSelectedDivisions(getComboValueByIdList(divisionList,refEvent.selectedDivisions));
            setSelectedSubDivisions(getComboValueByIdList(subDivisionList,refEvent.selectedSubDivisions));

            setSelectedType(getComboValueByLabel(EVENT_TYPE_COMBO,refEvent.selectedType));
            setFromDate(
                refEvent.fromDate === null ? null : dayjs(refEvent.fromDate)
            );
            setToDate(
                refEvent.toDate === null ? null : dayjs(refEvent.toDate)
            );
        }
        else{
            resetForm();
        }
    }, [refEvent]);

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

// ==============================|| NEW TEMPLATE WINDOW RELATED ||============================== //
    const [isTempWindowOpen, setIsTempWindowOpen] = React.useState(false);
    const [templateName, setTemplateName] = React.useState(false);

    const handleTempClose = () => {
        setIsTempWindowOpen(false);
    };

    function uploadTemplate(){
        setIsTempWindowOpen(false);
        setIsUploading(true);
        const userData = getUserData();
        const data = getValues();
        const temp = {
            eventName: data.eventName,
            description: data.description,
            organization: data.organization,
            selectedRegion: selectedRegion === null ? null : selectedRegion.label,
            selectedType: selectedType === null ? null : selectedType.label,
            selectedDivisions: selectedDivisions.length <1 ? [] : getIdList(selectedDivisions),
            selectedSubDivisions: selectedSubDivisions.length <1 ? [] : getIdList(selectedSubDivisions),
            fromDate: fromDate === null ? null : dayjs(fromDate).format('YYYY-MM-DD'),
            toDate: toDate === null ? null : dayjs(toDate).format('YYYY-MM-DD'),
        };

        let templateSet={
            id: -1,
            userId: userData.id,
            name: templateName.trim(),
            module: "Event",
            criteria: JSON.stringify(temp),
        }
        axios.post(`${apiPath}${POST_SEARCH_TEMPLATE_PATH}`,
            templateSet,
        )
            .then((response) => {
                if (response.status === 200) {
                    setIsUploading(false);
                    getTemplateList();
                    notifySaveSuccess();
                }
            })
            .catch(error => {
                setIsUploading(false);
                console.log(error);
                return false;
            });
    }

    const createNewTemplate = () => {
        setIsTempWindowOpen(true);
    };

// ==============================|| NEW TEMPLATE WINDOW RELATED ||============================== //

    const createNewEvent = () => {
        navigate(`/event/maintain/-1`);
    };

    const onSubmit = (data) => {
        const temp = {
            ...data,
            fromDate: fromDate === null ? null : dayjs(fromDate).format('YYYY-MM-DD'),
            toDate: toDate === null ? null : dayjs(toDate).format('YYYY-MM-DD'),
            region: selectedRegion === null ? null : selectedRegion.label,
            type: selectedType === null ? null :selectedType.label,
            divisionIdList: getIdList(selectedDivisions),
            subDivisionIdList: getIdList(selectedSubDivisions),
        };
        applySearch(temp);
        setExpanded(false);
    };

    function onExport(){
        const data = getValues();
        const temp = {
            ...data,
            fromDate: fromDate === null ? null : dayjs(fromDate).format('YYYY-MM-DD'),
            toDate: toDate === null ? null : dayjs(toDate).format('YYYY-MM-DD'),
            region: selectedRegion === null ? null : selectedRegion.label,
            type: selectedType === null ? null :selectedType.label,
            divisionIdList: getIdList(selectedDivisions),
            subDivisionIdList: getIdList(selectedSubDivisions),
        };
        setIsUploading(true);
        axios.get(`${apiPath}${GET_EVENT_EXPORT}`,{
            responseType: 'blob',
            params: temp,
            paramsSerializer: function (params) {
                return Qs.stringify(params, { arrayFormat: 'repeat' });
            },
        })
            .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", "event_export_"+ Date.now() + ".xlsx");
                    link.click();
                }
            })
            .catch(error => {
                setIsUploading(false);
                console.log(error);
                return false;
            });
    }

    function getSubDivisionCombo(divisionIds){
        axios.get(`${apiPath}${GET_SUB_DIVISION_COMBO_LIST}`,
            {
                params: {
                    "divisionIds": divisionIds
                },
                paramsSerializer: function (params) {
                    return Qs.stringify(params, { arrayFormat: 'repeat' });
                },
            })
            .then((response) => {
                if (response.status === 200) {
                    setSubDivisionList(response.data.records);
                    if(!isObjEmpty(refEvent) && isUpdating){
                        setSelectedSubDivisions(getComboValueByIdList(response.data.records,refEvent.selectedSubDivisions));
                        setIsUpdating(false);
                    }
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    function getDivisionCombo(){
        axios.get(`${apiPath}${GET_DIVISION_COMBO_LIST}`)
            .then((response) => {
                if (response.status === 200) {
                    setDivisionList(response.data.records);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    useEffect(() => {
        getDivisionCombo();
        getSubDivisionCombo(null);
        const year = queryParams.get('year');
        if(year !== null){
            setFromDate(
                dayjs(year+"-01-01 00:00:00")
            );
            setToDate(
                dayjs(year+"12-31")
            );
        }
    }, []);

    useEffect(() => {
        const userSubDivision = queryParams.get('userSubDivision');
        if(userSubDivision === "true" &&
            !isObjEmpty(userDivision) &&
            !isObjEmpty(divisionList)){
            setSelectedDivisions(getComboValueByIdList(divisionList,[userDivision.id]));
        }
    }, [userDivision,divisionList]);

    // useEffect(() => {
    //     if(selectedDivisions !== null && selectedDivisions !== undefined){
    //         const temp = selectedDivisions.length > 0 ? getIdList(selectedDivisions) : [];
    //         //const idList = castListToString(temp);
    //         getSubDivisionCombo(temp);
    //     }
    //     if(selectedDivisions.length <=0){
    //         setSelectedSubDivisions([]);
    //     }
    // }, [selectedDivisions]);
    //
    // useEffect(() => {
    //     removeInvalidSubDivision(getIdList(selectedDivisions));
    // }, [subDivisionList]);
    //
    // function removeInvalidSubDivision (divisionIdList){
    //     let temp = selectedSubDivisions;
    //     let output = [];
    //     for(let i=0 ; i<temp.length; i++){
    //         for(let j=0 ; j<temp.length; j++){
    //             if(temp[i].divisionId === divisionIdList[j]){
    //                 output.push(temp[i]);
    //             }
    //         }
    //     }
    //     setSelectedSubDivisions(
    //         getComboValueByIdList(
    //             subDivisionList,
    //             getIdList(output),
    //         ));
    // }

    function resetForm(){
        setSelectedSubDivisions([]);
        setSelectedDivisions([]);
        setSelectedRegion(null);
        setSelectedType(null);
        setFromDate(null);
        setToDate(null);
        reset();
    }

    return (
        <MainCard xs={12} md={12} lg={12}
                  content={false}
                  sx={{width:CARD_MAX_WIDTH}}
        >
            <Grid item onClick={handleExpandClick}>
            <CardActions disableSpacing>
                {/*row 1*/}
                <Grid item justifyContent="space-between" alignItems="center" sx={{mt:1,ml:2,mb:1}}>
                    <Typography variant="lionerSubLabel" >
                        Search Criteria(s)
                    </Typography>
                </Grid>

                <ExpandMore
                    expand={expanded.toString()}
                    onClick={handleExpandClick}
                    aria-expanded={expanded}
                    aria-label="show more"
                    style={{ marginLeft: 'auto' }} // Align the button to the right
                >
                    <ExpandMoreIcon />
                </ExpandMore>
            </CardActions>
            </Grid>

            <Collapse in={expanded} timeout="auto" unmountOnExit>
                <form onSubmit={handleSubmit(onSubmit)}>
                <ThemeProvider theme={LIONER_FORM_THEME}>
                {/*row 2*/}
                <Grid container alignItems={"flex-start"} >
                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5}}>
                        <InputLabel htmlFor="eventName">Event Name</InputLabel>
                        <TextField
                            fullWidth
                            {...register("eventName")}
                            id='eventName'
                            inputProps={{maxLength: 255}}
                            //label="Event Name"
                            autoComplete="off"
                        />
                    </Grid>

                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5}}>
                        <InputLabel htmlFor="eventName">Event Description</InputLabel>
                        <TextField
                            fullWidth
                            {...register("description")}
                            inputProps={{maxLength: 500}}
                            id="description"
                            autoComplete="off"
                        />
                    </Grid>

                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5}}>
                        <InputLabel htmlFor="eventName">Event Organization</InputLabel>
                        <TextField
                            fullWidth
                            inputProps={{maxLength: 255}}
                            {...register("organization")}
                            id="organization"
                            autoComplete="off"
                        />
                    </Grid>

                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5}}>
                        <InputLabel htmlFor="eventName">Event Region</InputLabel>
                        <Autocomplete
                            disablePortal
                            id="region-combo"
                            size="small"
                            value={selectedRegion === null? null : selectedRegion}
                            options={EVENT_REGION_COMBO}
                            onChange={(event, newValue) => {
                                setSelectedRegion(newValue);
                            }}
                            renderInput={(params) => <TextField {...params}/>}
                            isOptionEqualToValue={isOptionEqualToValue}
                        />
                    </Grid>

                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5}}>
                        <InputLabel htmlFor="eventName">Event Type</InputLabel>
                        <Autocomplete
                            disablePortal
                            id="event-type-combo"
                            size="small"
                            value={selectedType === null? null : selectedType}
                            options={EVENT_TYPE_COMBO}
                            onChange={(event, newValue) => {
                                setSelectedType(newValue);
                            }}
                            renderInput={(params) => <TextField {...params} />}
                            isOptionEqualToValue={isOptionEqualToValue}
                        />
                    </Grid>

                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5}}>
                        <InputLabel htmlFor="eventName">Application Date From</InputLabel>

                        <Grid container>
                            <Grid item xs={5.25} s={5.25} md={5.25} lg={5.5}>
                                <LocalizationProvider dateAdapter={AdapterDayjs}>
                                    <DemoItem>
                                        <DatePicker
                                            id="fromDate"
                                            onError={(newError) => setFromError(newError)}
                                            slotProps={{
                                                field: { clearable: true },
                                                textField: {
                                                    helperText: fromErrorMessage,
                                                },
                                            }}
                                            format="DD/MM/YYYY"
                                            value={fromDate === null ? null : dayjs(fromDate)}
                                            onChange={(newValue) => setFromDate(newValue)}
                                        />
                                    </DemoItem >
                                </LocalizationProvider>
                            </Grid>

                            <Grid item xs={1.5} s={1.5} md={1.5} lg={1} sx={{mt:1.3, display: 'flex', justifyContent:"center", alignItems: 'flex-start'}}>
                                To
                            </Grid>

                            <Grid item xs={5.25} s={5.25} md={5.25} lg={5.5}>
                                <LocalizationProvider dateAdapter={AdapterDayjs}>
                                    <DemoItem  components={['DatePicker']}>
                                        <DatePicker
                                            format="DD/MM/YYYY"
                                            onError={(newError) => setToError(newError)}
                                            slotProps={{
                                                field: { clearable: true },
                                                textField: {
                                                    helperText: toErrorMessage,
                                                },
                                            }}
                                            id="toDate"
                                            //label="To Date"
                                            value={toDate === null ? null : dayjs(toDate)}
                                            onChange={(newValue) => setToDate(newValue)}
                                        />
                                    </DemoItem >
                                </LocalizationProvider>
                            </Grid>
                        </Grid>
                    </Grid>

                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5}}>
                        <InputLabel htmlFor="eventName">Division</InputLabel>
                        <Autocomplete
                            multiple
                            disablePortal
                            id="division-combo"
                            size="small"
                            value={selectedDivisions === null? null : selectedDivisions}
                            options={divisionList}
                            onChange={(event, newValue) => {
                                setSelectedDivisions(newValue);
                            }}
                            renderInput={(params) => <TextField {...params} />}
                            isOptionEqualToValue={isOptionEqualToValue}
                        />
                    </Grid>

                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5}}>
                        <InputLabel htmlFor="eventName">Sub-Division</InputLabel>
                        <Autocomplete
                            multiple
                            disablePortal
                            id="sub-division-combo"
                            size="small"
                            value={selectedSubDivisions === null? null : selectedSubDivisions}
                            options={subDivisionList}
                            //disabled={selectedDivisions.length<=0}
                            onChange={(event, newValue) => {
                                setSelectedSubDivisions(newValue);
                            }}
                            renderInput={(params) => <TextField {...params} />}
                            isOptionEqualToValue={isOptionEqualToValue}
                        />
                    </Grid>

                </Grid>


                {/*last row*/}
                <Grid container maxWidth justifyContent="space-between" sx={{mt:1.5}}>
                    <ThemeProvider theme={LIONER_BUTTON_THEME}>
                    <Grid item>
                        <Grid container>
                            <Grid item sx={{ml:3, mr:1.5, mb:2}}>
                                <Button
                                    variant="contained"
                                    type="submit"
                                    color="save"
                                    disabled={fromError || toError}
                                >
                                    Search
                                </Button>
                            </Grid>

                            <Grid item sx={{ml:1.5, mr:1.5, mb:2}}>
                                <Button
                                    variant="contained"
                                    color="export"
                                    onClick={onExport}
                                    disabled={fromError || toError}
                                >
                                    Export
                                </Button>
                            </Grid>

                            <Grid item sx={{ml:{xs:1.5, md:1.5, lg:1.5}, mr:1.5, mb:2}}>
                                <Button
                                    variant="contained"
                                    color="cancel"
                                    onClick={resetForm}>
                                    Clear
                                </Button>
                            </Grid>

                            <Grid item sx={{ml:{xs:3, md:3, lg:1.5}, mr:3, mb:2}}>
                                <ThemeProvider theme={LIONER_LONG_BUTTON_THEME}>
                                <Button
                                    variant="contained"
                                    color="saveAs"
                                    onClick={createNewTemplate}
                                    disabled={fromError || toError}
                                >
                                    Save As Template
                                </Button>
                                </ThemeProvider>

                                <GeneralCreateTemplateWindow
                                    isWindowOpen={isTempWindowOpen}
                                    title={"New Event Template"}
                                    content={"Event Template Name"}
                                    validatePath={VALIDATE_TEMPLATE_NAME_PATH}
                                    setValueCallback={setTemplateName}
                                    onNormalClose={handleTempClose}
                                    onConfirmClose={uploadTemplate}
                                    module={"Event"}
                                />
                            </Grid>
                        </Grid>
                    </Grid>

                    <Grid item>
                        <Grid container>
                            {ability.can('EDIT','EVENT') ?
                                <Grid item sx={{ml:3, mr:3, mb:0.5}}>
                                    <Button
                                        variant="contained"
                                        color="create"
                                        onClick={createNewEvent}>
                                        New Event
                                    </Button>
                                </Grid>
                                :
                                <Grid/>
                            }
                        </Grid>
                    </Grid>
                    </ThemeProvider>
                </Grid>
                </ThemeProvider>
            </form>
            </Collapse>
        </MainCard>
    );
};

export default EventSearchForm;
