// material-ui
import {
    Button,
    Typography,
    Grid, InputLabel, TextField, 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_APPLICATION_EXPORT,
    GET_DIVISION_COMBO_LIST, GET_EVENT_COMBO_PATH, GET_LDAP_USER_LIST,
    GET_SUB_DIVISION_COMBO_LIST,
    GET_TAG_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 {
    convertXmlToObject,
    GeneralComboWindow, GeneralCreateTemplateWindow,
    getComboValueByIdList, getComboValueByLabel,
    getIdList, isOptionEqualToValue, notifySaveSuccess,
} from "../../utils/CommonFunction";
import Qs from 'qs';
import {useNavigate} from "react-router";
import {ThemeProvider} from "@emotion/react";
import {isObjEmpty} from "../../utils/Utils";
import UploadContext from "../../components/UploadProvider";
import {APPLICATION_STATUS_COMBO} from "../../utils/ComboConst";
import {parseString} from "xml2js";
import AbilityContext from "../../components/AbilityProvider";
import Collapse from '@mui/material/Collapse';
import {ExpandMore} from "@mui/icons-material";
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import {CARD_MAX_WIDTH} from "../../themes/themeConst";
// ==============================|| DASHBOARD - DEFAULT ||============================== //

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

    const navigate = useNavigate()
    const ability = useContext(AbilityContext);
    const { setIsUploading } = useContext(UploadContext);
    const handleExpandClick = () => {
        setExpanded(!expanded);
    };

    const [selectedTag, setSelectedTag] = useState([]);
    const [selectedStatus, setSelectedStatus] = useState(null);
    const [selectedOfficer, setSelectedOfficer] = useState(null);
    const [selectedSubDivisions, setSelectedSubDivisions] = useState([]);
    const [selectedDivisions, setSelectedDivisions] = useState([]);
    const [selectedEvenet, setSelectedEvent] = useState(null);

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

    const [userEventComboList, setUserEventComboList] = useState([]);
    const { setValue, reset, register, handleSubmit, getValues } = useForm()

    const [lotusNoteUserList, setLotusNoteUserList] = useState([])
    const handleLocationCodeChange = (event, value) => {
        setSelectedOfficer({
            label: value,
        });
        if (value.length >2 && !value.includes("(")) {
            fetchLotusUserList(value);
        } else {
            setLotusNoteUserList(lotusNoteUserList);
        }
    };
    // Function to fetch user name options based on locationCode
    const fetchLotusUserList = async (input) => {
        try {
            axios.get(`${apiPath}${GET_LDAP_USER_LIST}`,{
                params:{
                    "EMSDlotus": input,
                }
            })
                .then((response) => {
                    if (response.status === 200) {
                        let xml = response.data;
                        parseString(xml, function (err, result) {
                            // if(!isObjEmpty(refApplication) && isUpdating){
                            //     setSelectedOfficer(
                            //         getComboValueByLabel(convertXmlToObject(result.RECORDS.RECORD),
                            //             refApplication.selectedOfficer));
                            // }
                            setLotusNoteUserList(convertXmlToObject(result.RECORDS.RECORD));
                        });

                    }
                })
                .catch(error => {
                    console.log(error);
                    return false;
                });
        } catch (error) {
            console.error('Error fetching user name options:', error);
        }
    };

    //=====TEMPLATE RELATED START=====//
    const [refApplication, setRefApplication] = useState(null);

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

    useEffect(() => {
        if(!isObjEmpty(refApplication)){
            if(refApplication.selectedOfficer !== null){
                //const locationCode = .split('(')[1].replace(')','');
                fetchLotusUserList(refApplication.selectedOfficer);
            }
            else{
                setSelectedOfficer(null);
            }
            setValue('eventName', refApplication.eventName );
            setValue('applicationName', refApplication.applicationName );
            setValue('description', refApplication.description );
            setSelectedTag(getComboValueByIdList(tagList,refApplication.selectedTag));
            setSelectedDivisions(getComboValueByIdList(divisionList,refApplication.selectedDivisions));
            setSelectedSubDivisions(getComboValueByIdList(subDivisionList,refApplication.selectedSubDivisions));
            setSelectedOfficer(refApplication.selectedOfficer);
            setSelectedStatus(getComboValueByLabel(APPLICATION_STATUS_COMBO,refApplication.selectedStatus));
        }
        else{
            resetForm();
        }
    }, [refApplication]);

    useEffect(() => {
        setRefApplication(refTemplateData);
    }, [subDivisionList]);
    //=====TEMPLATE RELATED END=====//

// ==============================|| NEW WINDOW RELATED START||============================== //
    const [isWindowOpen, setIsWindowOpen] = React.useState(false);
    const handleClose = () => {
        setIsWindowOpen(false);
    };

    function updateData(){
        setIsWindowOpen(false);
        navigate(`/application/maintain/-1/${selectedEvenet.id}`);
    }

    const createNewApplication = () => {
        setIsWindowOpen(true);
    };
// ==============================|| NEW WINDOW 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,
            applicationName: data.applicationName,
            description: data.description,
            selectedStatus: selectedStatus === null ? null :selectedStatus.label,
            selectedOfficer: selectedOfficer ? null : selectedOfficer.label,
            selectedTag: getIdList(selectedTag),
            selectedDivisions: getIdList(selectedDivisions),
            selectedSubDivisions: getIdList(selectedSubDivisions),
        };

        let templateSet={
            id: -1,
            userId: userData.id,
            name: templateName.trim(),
            module: "Application",
            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 onSubmit = (data) => {
        const temp = {
            eventName: data.eventName,
            applicationName: data.applicationName,
            description: data.description,
            status: selectedStatus === null ? null :selectedStatus.label,
            officer: isObjEmpty(selectedOfficer) ? null : selectedOfficer.label,
            tagList: getIdList(selectedTag),
            divisionIdList: getIdList(selectedDivisions),
            subDivisionIdList: getIdList(selectedSubDivisions),
        };
        applySearch(temp);
        setExpanded(false);
    };

    function onExport(){
        const data = getValues();
        const temp = {
            eventName: data.eventName,
            applicationName: data.applicationName,
            description: data.description,
            status: selectedStatus === null ? null :selectedStatus.label,
            officer: isObjEmpty(selectedOfficer) ? null : selectedOfficer.label,
            tagList: getIdList(selectedTag),
            divisionIdList: getIdList(selectedDivisions),
            subDivisionIdList: getIdList(selectedSubDivisions),
            userSubDivisionId: ability.can('VIEW', 'ALL_RECORD') ? null : localStorage.getItem('subDivisionId'),
        };
        setIsUploading(true);
        axios.get(`${apiPath}${GET_APPLICATION_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", "application_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(refApplication) && isUpdating){
                        setSelectedSubDivisions(getComboValueByIdList(response.data.records,refApplication.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;
            });
    }

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

    function getUserEventCombo(){
        axios.get(`${apiPath}${GET_EVENT_COMBO_PATH}`,{
            params:{
                userSubDivisionId: ability.can('EDIT','ALL_RECORD') ? null : localStorage.getItem('subDivisionId'),
            }
        })
            .then((response) => {
                if (response.status === 200) {
                    setUserEventComboList(response.data.records);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    useEffect(() => {
        getTagCombo();
        getUserEventCombo();
        getDivisionCombo();
        getSubDivisionCombo(null);
    }, []);

    // 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([]);
        setSelectedTag([]);
        setSelectedStatus(null);
        setSelectedOfficer("");
        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)}>
                {/*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
                            inputProps={{maxLength: 255}}
                            {...register("eventName")}
                            id='eventName'
                            autoComplete="off"
                        />
                    </Grid>

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

                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5}}>
                        <InputLabel htmlFor="eventName">Application Description</InputLabel>
                        <TextField
                            fullWidth
                            inputProps={{maxLength: 500}}
                            {...register("description")}
                            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">Tag</InputLabel>
                        <Autocomplete
                            multiple
                            disablePortal
                            id="tag-combo"
                            size="small"
                            value={selectedTag === null? null : selectedTag}
                            options={tagList}
                            onChange={(event, newValue) => {
                                setSelectedTag(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">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 item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5}}>
                        <InputLabel htmlFor="eventName">Responsible Officer</InputLabel>
                        <Autocomplete
                            disablePortal
                            id="lotus-note-combo"
                            value={selectedOfficer === null ? null : selectedOfficer}
                            options={lotusNoteUserList}
                            size="small"
                            freeSolo
                            onInputChange={handleLocationCodeChange}
                            onChange={(event, newValue) => {
                                setSelectedOfficer(newValue);
                                // if(lotusNoteUserList.length >0){
                                //     if(newValue !== null){
                                //         if(getComboValueByLabel(lotusNoteUserList, newValue.label) !== null){
                                //             setSelectedOfficer(newValue);
                                //         }
                                //     }
                                //     else{
                                //         setSelectedOfficer(null);
                                //     }
                                // }
                            }}
                            renderInput={(params) => <TextField
                                {...params}
                                InputProps={{
                                    ...params.InputProps,
                                    inputProps: {
                                        ...params.inputProps,
                                        maxLength: 100
                                    }
                                }}
                            />}
                        />
                    </Grid>

                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5}}>
                        <InputLabel htmlFor="eventName">Status</InputLabel>
                        <Autocomplete
                            disablePortal
                            id="status-combo"
                            size="small"
                            value={selectedStatus === null? null : selectedStatus}
                            options={APPLICATION_STATUS_COMBO}
                            onChange={(event, newValue) => {
                                setSelectedStatus(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">
                                    Search
                                </Button>
                            </Grid>

                            <Grid item sx={{ml:1.5, mr:1.5, mb:2}}>
                                <Button
                                    variant="contained"
                                    color="export"
                                    onClick={onExport}>
                                    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}>
                                    Save As Template
                                </Button>
                                </ThemeProvider>
                                <GeneralCreateTemplateWindow
                                    isWindowOpen={isTempWindowOpen}
                                    title={"New Application Template"}
                                    content={"Application Template Name"}
                                    validatePath={VALIDATE_TEMPLATE_NAME_PATH}
                                    setValueCallback={setTemplateName}
                                    onNormalClose={handleTempClose}
                                    onConfirmClose={uploadTemplate}
                                    module={"Application"}
                                />
                            </Grid>
                        </Grid>
                    </Grid>

                    <Grid item>
                        <Grid container>
                            {
                                ability.can('EDIT','APPLICATION') ?
                                    <Grid item sx={{ml:3, mr:1.5, mb:0.5}}>
                                        <ThemeProvider theme={LIONER_LONG_BUTTON_THEME}>
                                        <Button
                                            variant="contained"
                                            color="create"
                                            onClick={createNewApplication}>
                                            New Application
                                        </Button>
                                        </ThemeProvider>
                                        <GeneralComboWindow
                                            isWindowOpen={isWindowOpen}
                                            title={"New Application"}
                                            content={"Event"}
                                            comboList={userEventComboList}
                                            setValueCallback={setSelectedEvent}
                                            onNormalClose={handleClose}
                                            onConfirmClose={updateData}
                                        />
                                    </Grid>
                                    :
                                    <Grid/>
                            }
                        </Grid>
                    </Grid>
                    </ThemeProvider>
                </Grid>
            </form>
            </Collapse>
        </MainCard>
    );
};

export default ApplicationSearchForm;
