import {Grid, TextField, Typography} from "@mui/material";
import * as React from "react";
import {useEffect, useState} from "react";
import Autocomplete from "@mui/material/Autocomplete";
import axios from "axios";
import {apiPath} from "../../auth/utils";
import {
    GET_DIVISION_COMBO_LIST, GET_LDAP_USER_LIST,
    GET_SUB_DIVISION_COMBO_LIST, GET_TAG_COMBO_LIST
} from "../../utils/ApiPathConst";
import Qs from "qs";
import {
    convertXmlToObject,
    getComboValueByIdList,
    getComboValueByLabel,
    getIdList,
    isOptionEqualToValue
} from "../../utils/CommonFunction";
import {useParams} from "react-router-dom";
import LoadingComponent from "../extra-pages/LoadingComponent";
import {APPLICATION_STATUS_COMBO} from "../../utils/ComboConst";
import {isObjEmpty} from "../../utils/Utils";
import {parseString} from "xml2js";

export default function ApplicationTemplateForm({setValue, setIsReset, refTemplateData, isReset, isCollectData, applyTemplateValue, register}) {
    const params = useParams();
    const [onReady, setOnReady] = useState(false);

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

    const [refApplication, setRefApplication] = useState({});

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

    const [lotusNoteUserList, setLotusNoteUserList] = useState([])
    const handleLocationCodeChange = (event, value) => {
        setSelectedOfficer({
            label: value,
        });
        if (value.length >2 && !value.includes("(")) {
            fetchLotusUserList(value,false);
        } else {
            setLotusNoteUserList(lotusNoteUserList);
        }
    };

    // Function to fetch user name options based on locationCode
    const fetchLotusUserList = async (input, isInit) => {
        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(refTemplateData) && isInit){
                                setSelectedOfficer(
                                    getComboValueByLabel(convertXmlToObject(result.RECORDS.RECORD),
                                        refTemplateData.selectedOfficer));
                            }
                            setLotusNoteUserList(convertXmlToObject(result.RECORDS.RECORD));
                        });

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

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

    useEffect(() => {
        if(isReset){
            setValue('eventName', "" );
            setValue('applicationName', "" );
            setValue('description', "" );
            setSelectedSubDivisions([]);
            setSelectedDivisions([]);
            setSelectedTag([]);
            setSelectedStatus(null);
            setSelectedOfficer("");
            setIsReset(false)
        }

    }, [isReset]);

    useEffect(()=>{
        if(tagList.length > 0 &&
            subDivisionList.length > 0 &&
            divisionList.length > 0
        ){
            setRefApplication(refTemplateData);
        }
    },[tagList,subDivisionList,divisionList]);

    useEffect(() => {
        if (Object.keys(refApplication).length > 0
            && params.id > 0
        ) {
            if(refTemplateData.selectedOfficer !== null){
                //const locationCode = refTemplateData.selectedOfficer.split('(')[1].replace(')','');
                fetchLotusUserList(refTemplateData.selectedOfficer,true);
            }
            setSelectedTag(getComboValueByIdList(tagList,refApplication.selectedTag));
            setSelectedDivisions(getComboValueByIdList(divisionList,refApplication.selectedDivisions));
            setSelectedSubDivisions(getComboValueByIdList(subDivisionList,refApplication.selectedSubDivisions));
            setSelectedStatus(getComboValueByLabel(APPLICATION_STATUS_COMBO,refApplication.selectedStatus));
            setOnReady(true);
        }
        else if ( params.id < 0){
            setOnReady(true);
        }
    }, [refApplication]);

    useEffect(() => {
        if(isCollectData){
            let data = {
                selectedTag: selectedTag.length <1 ? [] : getIdList(selectedTag),
                selectedStatus: selectedStatus === null ? null : selectedStatus.label,
                selectedOfficer: selectedOfficer === null ? null : selectedOfficer.label,
                selectedDivisions: selectedDivisions.length <1 ? [] : getIdList(selectedDivisions),
                selectedSubDivisions: selectedSubDivisions.length <1 ? [] : getIdList(selectedSubDivisions),
            };
            applyTemplateValue(data);
        }
    }, [isCollectData]);

    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);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    // useEffect(() => {
    //     if(selectedDivisions !== null && selectedDivisions !== undefined){
    //         const temp = selectedDivisions.length > 0 ? getIdList(selectedDivisions) : [];
    //         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 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;
            });
    }

    return !onReady ?
        <LoadingComponent/>
        :
        <Grid container>
            <Grid item xs={12} s={12} md={12} lg={12} sx={{ml:3, mr:3, mb:3}}>
                <Grid container >
                    <Grid item xs={12} s={12} md={12} lg={2} sx={{display: 'flex', alignItems: 'center'}}>
                        <Typography variant="lionerSize" component="span">
                            Event Name:
                        </Typography>
                    </Grid>

                    <Grid item xs={12} s={12} md={12} lg={6} justifyContent="space-between" alignItems="right">
                        <TextField
                            fullWidth
                            inputProps={{maxLength: 255}}
                            {...register("eventName",{
                                value:  refApplication === null ? null : refApplication.eventName,
                            })}
                            id='eventName'
                            autoComplete="off"
                        />
                    </Grid>
                </Grid>
            </Grid>

            <Grid item xs={12} s={12} md={12} lg={12} sx={{ml:3, mr:3, mb:3}}>
                <Grid container >
                    <Grid item xs={12} s={12} md={12} lg={2} sx={{display: 'flex', alignItems: 'center'}}>
                        <Typography variant="lionerSize" component="span">
                            Application Name:
                        </Typography>
                    </Grid>

                    <Grid item xs={12} s={12} md={12} lg={6} justifyContent="space-between" alignItems="right">
                        <TextField
                            fullWidth
                            inputProps={{maxLength: 255}}
                            {...register("applicationName",{
                                value:  refApplication === null ? null : refApplication.applicationName,
                            })}
                            id="applicationName"
                            autoComplete="off"
                        />
                    </Grid>
                </Grid>
            </Grid>

            <Grid item xs={12} s={12} md={12} lg={12} sx={{ml:3, mr:3, mb:3}}>
                <Grid container >
                    <Grid item xs={12} s={12} md={12} lg={2} sx={{display: 'flex', alignItems: 'center'}}>
                        <Typography variant="lionerSize" component="span">
                            Application Description:
                        </Typography>
                    </Grid>

                    <Grid item xs={12} s={12} md={12} lg={6} justifyContent="space-between" alignItems="right">
                        <TextField
                            fullWidth
                            inputProps={{maxLength: 500}}
                            {...register("description",{
                                value:  refApplication === null ? null : refApplication.description,
                            })}
                            id="description"
                            autoComplete="off"
                        />
                    </Grid>
                </Grid>
            </Grid>

            <Grid item xs={12} s={12} md={12} lg={12} sx={{ml:3, mr:3, mb:3}}>
                <Grid container >
                    <Grid item xs={12} s={12} md={12} lg={2} sx={{display: 'flex', alignItems: 'center'}}>
                        <Typography variant="lionerSize" component="span">
                            Tag:
                        </Typography>
                    </Grid>

                    <Grid item xs={12} s={12} md={12} lg={6} justifyContent="space-between" alignItems="right">
                        <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>
            </Grid>

            <Grid item xs={12} s={12} md={12} lg={12} sx={{ml:3, mr:3, mb:3}}>
                <Grid container >
                    <Grid item xs={12} s={12} md={12} lg={2} sx={{display: 'flex', alignItems: 'center'}}>
                        <Typography variant="lionerSize" component="span">
                            Division:
                        </Typography>
                    </Grid>

                    <Grid item xs={12} s={12} md={12} lg={6} justifyContent="space-between" alignItems="right">
                        <Autocomplete
                            multiple
                            disablePortal
                            id="division-combo"
                            size="small"
                            value={selectedDivisions === null? null : selectedDivisions}
                            options={divisionList}
                            onChange={(event, newValue) => {
                                setSelectedDivisions(newValue);
                            }}
                            isOptionEqualToValue={isOptionEqualToValue}
                            renderInput={(params) => <TextField {...params} />}
                        />
                    </Grid>
                </Grid>
            </Grid>

            <Grid item xs={12} s={12} md={12} lg={12} sx={{ml:3, mr:3, mb:3}}>
                <Grid container >
                    <Grid item xs={12} s={12} md={12} lg={2} sx={{display: 'flex', alignItems: 'center'}}>
                        <Typography variant="lionerSize" component="span">
                            Sub-Division:
                        </Typography>
                    </Grid>

                    <Grid item xs={12} s={12} md={12} lg={6} justifyContent="space-between" alignItems="right">
                        <Autocomplete
                            multiple
                            disablePortal
                            id="sub-division-combo"
                            size="small"
                            value={selectedSubDivisions === null? null : selectedSubDivisions}
                            options={subDivisionList}
                            //disabled={selectedDivisions === null}
                            onChange={(event, newValue) => {
                                setSelectedSubDivisions(newValue);
                            }}
                            isOptionEqualToValue={isOptionEqualToValue}
                            renderInput={(params) => <TextField {...params} />}
                        />
                    </Grid>
                </Grid>
            </Grid>

            <Grid item xs={12} s={12} md={12} lg={12} sx={{ml:3, mr:3, mb:3}}>
                <Grid container >
                    <Grid item xs={12} s={12} md={12} lg={2} sx={{display: 'flex', alignItems: 'center'}}>
                        <Typography variant="lionerSize" component="span">
                            Responsible Officer:
                        </Typography>
                    </Grid>

                    <Grid item xs={12} s={12} md={12} lg={6} justifyContent="space-between" alignItems="right">
                        <Autocomplete
                            disablePortal
                            id="lotus-note-combo"
                            value={selectedOfficer === null ? null : selectedOfficer}
                            options={lotusNoteUserList}
                            size="small"
                            freeSolo
                            onInputChange={handleLocationCodeChange}
                            onChange={(event, newValue) => {
                                setSelectedOfficer(newValue);
                            }}
                            isOptionEqualToValue={isOptionEqualToValue}
                            renderInput={(params) => <TextField
                                {...params}
                                InputProps={{
                                    ...params.InputProps,
                                    inputProps: {
                                        ...params.inputProps,
                                        maxLength: 100
                                    }
                                }}
                            />}
                        />
                    </Grid>
                </Grid>
            </Grid>

            <Grid item xs={12} s={12} md={12} lg={12} sx={{ml:3, mr:3, mb:3}}>
                <Grid container >
                    <Grid item xs={12} s={12} md={12} lg={2} sx={{display: 'flex', alignItems: 'center'}}>
                        <Typography variant="lionerSize" component="span">
                            Status:
                        </Typography>
                    </Grid>

                    <Grid item xs={12} s={12} md={12} lg={6} justifyContent="space-between" alignItems="right">
                        <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>
            </Grid>
        </Grid>

}