// 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, useRef, 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_COMBO_PATH,
    GET_AWARD_EXPORT,
    GET_AWARD_EXPORT_TEMPLATE,
    GET_CATEGORY_COMBO_LIST,
    GET_DIVISION_COMBO_LIST,
    GET_EVENT_COMBO_PATH,
    GET_LDAP_USER_LIST,
    GET_PROMOTION_CHANNEL_COMBO_LIST,
    GET_SUB_DIVISION_COMBO_LIST,
    GET_TAG_COMBO_LIST,
    POST_AWARD_IMPORT,
    POST_SEARCH_TEMPLATE_PATH,
    VALIDATE_TEMPLATE_NAME_PATH
} from "../../utils/ApiPathConst";
import {LIONER_BUTTON_THEME, LIONER_LONG_BUTTON_THEME, LIONER_MEDIUM_BUTTON_THEME} from "../../themes/colorConst";
import {
    convertXmlToObject,
    GeneralCreateTemplateWindow,
    GeneralTwoComboWindow,
    getComboValueByIdList, getComboValueByLabel,
    getIdList, isOptionEqualToValue, notifyDeleteError, notifySaveSuccess,
} from "../../utils/CommonFunction";
import Qs from 'qs';
import {useNavigate} from "react-router";
import {ThemeProvider} from "@emotion/react";
import UploadContext from "../../components/UploadProvider";
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 {parseString} from "xml2js";
import {useLocation} from "react-router-dom";
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";
import {ImportResultWindow} from "../lionerAppreciationSearchPage/ImportResultWindow";
//import {ImportResultWindow} from "../lionerAppreciationSearchPage/ImportResultWindow";

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

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

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

    const [selectedTag, setSelectedTag] = useState([]);
    const [selectedChannels, setSelectedChannels] = useState([]);
    const [selectedOfficer, setSelectedOfficer] = useState(null);
    const [selectedSubDivisions, setSelectedSubDivisions] = useState([]);
    const [selectedDivisions, setSelectedDivisions] = useState([]);
    const [selectedEvent, setSelectedEvent] = useState(null);
    const [selectedCategories, setSelectedCategories] = useState([]);
    const [selectedApplication, setSelectedApplication] = useState(null);
    const [fromDate, setFromDate] = useState(null);
    const [toDate, setToDate] = useState(null);
    const [awardFromDate, setAwardFromDate] = useState(null);
    const [awardToDate, setAwardToDate] = useState(null);

    const [tagList, setTagList] = useState([]);
    const [channelList, setChannelList] = useState([]);
    const [categoryList, setCategoryList] = useState([]);
    const [subDivisionList, setSubDivisionList] = useState([]);
    const [divisionList, setDivisionList] = useState([]);
    const [eventList, setEventList] = useState([]);
    const [applicationList, setApplicationList] = useState([]);

    const { setValue, reset, register, handleSubmit, getValues } = useForm()
    const [eventFromError, setEventFromError] = React.useState(null);
    const [eventToError, setEventToError] = React.useState(null);
    const eventFromErrorMessage = React.useMemo(() => {
        switch (eventFromError) {
            case 'invalidDate': {
                return "Invalid date";
            }
        }
    }, [eventFromError]);

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

    const [awardFromError, setAwardFromError] = React.useState(null);
    const [awardToError, setAwardToError] = React.useState(null);

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

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


    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(refAward) && isUpdating){
                                setSelectedOfficer({
                                    label:refAward.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 [refAward, setRefAward] = useState(null);

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

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

    useEffect(() => {
        if(!isObjEmpty(refAward)){
            if(refAward.selectedOfficer !== null){
                //const locationCode = refAward.selectedOfficer.split('(')[1].replace(')','');
                fetchLotusUserList(refAward.selectedOfficer);
            }
            else{
                setSelectedOfficer(null);
            }
            setValue('eventName', refAward.eventName );
            setValue('applicationName', refAward.applicationName );
            setValue('awardName', refAward.awardName );
            setValue('storageLocation', refAward.storageLocation );
            setValue('physicalAward', refAward.physicalAward );
            setSelectedTag(getComboValueByIdList(tagList,refAward.selectedTag));
            setSelectedCategories(getComboValueByIdList(categoryList,refAward.selectedCategories));
            setSelectedDivisions(getComboValueByIdList(divisionList,refAward.selectedDivisions));
            setSelectedSubDivisions(getComboValueByIdList(subDivisionList,refAward.selectedSubDivisions));
            setSelectedChannels(getComboValueByIdList(channelList,refAward.selectedChannels));
            setSelectedOfficer(getComboValueByLabel(lotusNoteUserList,refAward.selectedOfficer));
            setFromDate(
                refAward.fromDate === null ? null : dayjs(refAward.fromDate)
            );
            setToDate(
                refAward.toDate === null ? null : dayjs(refAward.toDate)
            )
            setAwardFromDate(
                refAward.awardFromDate === null ? null : dayjs(refAward.awardFromDate)
            );
            setAwardToDate(
                refAward.awardToDate === null ? null : dayjs(refAward.awardToDate)
            )
        }
        else{
            resetForm();
        }
    }, [refAward]);
    //=====TEMPLATE RELATED END=====//

    // ==============================|| IMPORT TEMPLATE WINDOW RELATED ||============================== //
    const fileInputRef = useRef(null);
    const [importStatus, setImportStatus] = useState(0);
    const [eventCount, setEventCount] = useState(0);
    const [applicationCount, setApplicationCount] = useState(0);
    const [awardCount, setAwardCount] = useState(0);
    const [importErrorList, setImportErrorList] = useState([]);

    const handleFileInputChange = (event) => {
        setIsUploading(true);
        const selectedFile = event.target.files[0];
        if (selectedFile.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") {
            const formData = new FormData();
            formData.append('files', selectedFile);
            axios.post(`${apiPath}${POST_AWARD_IMPORT}`,
                formData,
                {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                    }
                }
            )
                .then((response) => {
                    if (response.status === 200) {
                        setEventCount(response.data.data.eventCount);
                        setApplicationCount(response.data.data.applicationCount);
                        setAwardCount(response.data.data.awardCount);
                        setImportErrorList(response.data.data.recordList);
                        setImportStatus(response.data.data.status);
                        displayImportResult();
                    }
                    setIsUploading(false);
                    fileInputRef.current.value = '';
                })
                .catch((error) => {
                    setIsUploading(false);
                    notifyDeleteError('Server busy, please try again later.');
                    console.log(error);
                    return false;
                });
        } else {
            // Handle case when selected file is not an Excel file
            setIsUploading(false);
            fileInputRef.current.value = '';
            // Show an error message to the user
            alert('Please select an Excel xlsx file.');
        }

    };

    const handleImportTemplateClick = () => {
        fileInputRef.current.click();
    };

    const [isResultWindowOpen, setIsResultWindowOpen] = React.useState(false);

    const handleWindowClose = (event, reason) => {
        if (reason && reason === "backdropClick")
            return;
        setIsResultWindowOpen(false);
    };

    const handleReload = () =>{
        setIsResultWindowOpen(false);
        const data = getValues();
        const temp = {
            eventName: data.eventName,
            applicationName: data.applicationName,
            fromDate: fromDate === null ? null : dayjs(fromDate).format('YYYY-MM-DD'),
            toDate: toDate === null ? null : dayjs(toDate).format('YYYY-MM-DD'),
            awardFromDate: awardFromDate === null ? null : dayjs(awardFromDate).format('YYYY-MM-DD'),
            awardToDate: awardToDate === null ? null : dayjs(awardToDate).format('YYYY-MM-DD'),
            awardName: data.awardName,
            categoryIds: getIdList(selectedCategories),
            tagIds: getIdList(selectedTag),
            divisionIdList: getIdList(selectedDivisions),
            subDivisionIdList: getIdList(selectedSubDivisions),
            storageLocation: data.storageLocation,
            physicalAward: data.physicalAward,
            promotionChannel: isObjEmpty(getIdList(selectedChannels)) ? null : "[" + getIdList(selectedChannels).toString() + "]" ,
            responsibleOfficer: isObjEmpty(selectedOfficer)  ? null : selectedOfficer.label,
        };

        applySearch(temp);
    }

    function displayImportResult(){
        setIsResultWindowOpen(true);
    }

    // ==============================|| IMPORT TEMPLATE WINDOW RELATED ||============================== //


    function downloadTemplate(){
        axios.get(`${apiPath}${GET_AWARD_EXPORT_TEMPLATE}`,{
            responseType: 'blob',
        })
            .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", response.headers.filename);
                    link.click();
                }
            })
            .catch(error => {
                setIsUploading(false);
                console.log(error);
                return false;
            });
    }

// ==============================|| 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,
            awardName: data.awardName,
            physicalAward: data.physicalAward,
            storageLocation: data.storageLocation,
            applicationName: data.applicationName,
            fromDate: fromDate === null ? null : dayjs(fromDate).format('YYYY-MM-DD'),
            toDate: toDate === null ? null : dayjs(toDate).format('YYYY-MM-DD'),
            selectedCategories: getIdList(selectedCategories),
            awardFromDate: awardFromDate === null ? null : dayjs(awardFromDate).format('YYYY-MM-DD'),
            awardToDate: awardToDate === null ? null : dayjs(awardToDate).format('YYYY-MM-DD'),
            selectedTag: getIdList(selectedTag),
            selectedDivisions: getIdList(selectedDivisions),
            selectedSubDivisions: getIdList(selectedSubDivisions),
            selectedChannels: getIdList(selectedChannels),
            selectedOfficer: selectedOfficer === null ? null : selectedOfficer.label,
        };

        let templateSet={
            id: -1,
            userId: userData.id,
            name: templateName.trim(),
            module: "Award",
            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 ||============================== //


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

    function updateData(){
        setIsWindowOpen(false);
        navigate(`/award/maintain/-1/${selectedEvent.id}/${selectedApplication.id}`);
    }

    const createNewAward = () => {
        setIsWindowOpen(true);
    };
// ==============================|| NEW WINDOW RELATED END ||============================== //

    const onSubmit = (data) => {
        const temp = {
            eventName: data.eventName,
            applicationName: data.applicationName,
            fromDate: fromDate === null ? null : dayjs(fromDate).format('YYYY-MM-DD'),
            toDate: toDate === null ? null : dayjs(toDate).format('YYYY-MM-DD'),
            awardFromDate: awardFromDate === null ? null : dayjs(awardFromDate).format('YYYY-MM-DD'),
            awardToDate: awardToDate === null ? null : dayjs(awardToDate).format('YYYY-MM-DD'),
            awardName: data.awardName,
            categoryIds: getIdList(selectedCategories),
            tagIds: getIdList(selectedTag),
            divisionIdList: getIdList(selectedDivisions),
            subDivisionIdList: getIdList(selectedSubDivisions),
            storageLocation: data.storageLocation,
            physicalAward: data.physicalAward,
            promotionChannel: isObjEmpty(getIdList(selectedChannels)) ? null : "[" + getIdList(selectedChannels).toString() + "]" ,
            responsibleOfficer: isObjEmpty(selectedOfficer)  ? null : selectedOfficer.label,
        };
        applySearch(temp);
        setExpanded(false);
    };

    function onExport(){
        const data = getValues();
        const temp = {
            eventName: data.eventName,
            applicationName: data.applicationName,
            fromDate: fromDate === null ? null : dayjs(fromDate).format('YYYY-MM-DD'),
            toDate: toDate === null ? null : dayjs(toDate).format('YYYY-MM-DD'),
            awardFromDate: awardFromDate === null ? null : dayjs(awardFromDate).format('YYYY-MM-DD'),
            awardToDate: awardToDate === null ? null : dayjs(awardToDate).format('YYYY-MM-DD'),
            awardName: data.awardName,
            categoryIds: getIdList(selectedCategories),
            tagIds: getIdList(selectedTag),
            divisionIdList: getIdList(selectedDivisions),
            subDivisionIdList: getIdList(selectedSubDivisions),
            storageLocation: data.storageLocation,
            physicalAward: data.physicalAward,
            promotionChannel: isObjEmpty(getIdList(selectedChannels)) ? null : "[" + getIdList(selectedChannels).toString() + "]" ,
            responsibleOfficer: isObjEmpty(selectedOfficer) ? null : selectedOfficer.label,
            userSubDivisionId: ability.can('VIEW', 'ALL_RECORD') ? null : localStorage.getItem('subDivisionId'),
        };
        setIsUploading(true);
        axios.get(`${apiPath}${GET_AWARD_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", "award_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(refAward) && isUpdating){
                        setSelectedSubDivisions(getComboValueByIdList(response.data.records,refAward.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 getChannelCombo(){
        axios.get(`${apiPath}${GET_PROMOTION_CHANNEL_COMBO_LIST}`)
            .then((response) => {
                if (response.status === 200) {
                    setChannelList(response.data.records);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    function getCategoryCombo(){
        axios.get(`${apiPath}${GET_CATEGORY_COMBO_LIST}`)
            .then((response) => {
                if (response.status === 200) {
                    setCategoryList(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 getEventCombo(){
        axios.get(`${apiPath}${GET_EVENT_COMBO_PATH}`,
            {
                params:{
                    userSubDivisionId: ability.can('EDIT','ALL_RECORD') ? null : localStorage.getItem('subDivisionId'),
                }
            })
            .then((response) => {
                if (response.status === 200) {
                    setEventList(response.data.records);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

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

    useEffect(() => {
        getTagCombo();
        getEventCombo();
        getDivisionCombo();
        getCategoryCombo();
        getChannelCombo();
        getApplicationCombo(null);
        getSubDivisionCombo(null);
        const year = queryParams.get('year');
        if(year !== null){
            setAwardFromDate(
                dayjs(year+"-01-01 00:00:00")
            );
            setAwardToDate(
                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(selectedEvent !== null && Object.keys(selectedEvent).length >= 0){
            getApplicationCombo(selectedEvent.id);
        }
    }, [selectedEvent]);

    // 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([]);
        setSelectedCategories([]);
        setSelectedOfficer("");
        setSelectedChannels([]);
        setFromDate(null);
        setToDate(null);
        setAwardToDate(null);
        setAwardFromDate(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)}>

                {/*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")}
                            inputProps={{maxLength: 255}}
                            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="applicationName">Application Name</InputLabel>
                        <TextField
                            fullWidth
                            {...register("applicationName")}
                            inputProps={{maxLength: 255}}
                            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="awardName">Award Name</InputLabel>
                        <TextField
                            fullWidth
                            {...register("awardName")}
                            inputProps={{maxLength: 255}}
                            id="awardName"
                            autoComplete="off"
                        />
                    </Grid>

                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5}}>
                        <InputLabel>Event Date From</InputLabel>
                        <Grid container>
                            <Grid item xs={5.25} s={5.25} md={5.25} lg={5.5}>
                                <LocalizationProvider dateAdapter={AdapterDayjs}>
                                    <DemoItem  components={['DatePicker']}>
                                        <DatePicker
                                            id="fromDate"
                                            onError={(newError) => setEventFromError(newError)}
                                            slotProps={{
                                                field: { clearable: true },
                                                textField: {
                                                    helperText: eventFromErrorMessage,
                                                },
                                            }}
                                            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
                                            id="toDate"
                                            onError={(newError) => setEventToError(newError)}
                                            slotProps={{
                                                field: { clearable: true },
                                                textField: {
                                                    helperText: eventToErrorMessage,
                                                },
                                            }}
                                            format="DD/MM/YYYY"
                                            //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>Award Date From</InputLabel>
                        <Grid container>
                            <Grid item xs={5.25} s={5.25} md={5.25} lg={5.5}>
                                <LocalizationProvider dateAdapter={AdapterDayjs}>
                                    <DemoItem  components={['DatePicker']}>
                                        <DatePicker
                                            id="awardFromDate"
                                            onError={(newError) => setAwardFromError(newError)}
                                            slotProps={{
                                                field: { clearable: true },
                                                textField: {
                                                    helperText: awardFromErrorMessage,
                                                },
                                            }}
                                            format="DD/MM/YYYY"
                                            value={awardFromDate === null ? null : dayjs(awardFromDate)}
                                            onChange={(newValue) => setAwardFromDate(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
                                            id="awardToDate"
                                            onError={(newError) => setAwardToError(newError)}
                                            slotProps={{
                                                field: { clearable: true },
                                                textField: {
                                                    helperText: awardToErrorMessage,
                                                },
                                            }}
                                            format="DD/MM/YYYY"
                                            //label="To Date"
                                            value={awardToDate === null ? null : dayjs(awardToDate)}
                                            onChange={(newValue) => setAwardToDate(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="category-combo">Category</InputLabel>
                        <Autocomplete
                            multiple
                            disablePortal
                            id="category-combo"
                            size="small"
                            value={selectedCategories === null? null : selectedCategories}
                            options={categoryList}
                            onChange={(event, newValue) => {
                                setSelectedCategories(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="tag-combo">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="division-combo">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="sub-division-combo">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="lotus-note-combo">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);
                            }}
                            isOptionEqualToValue={isOptionEqualToValue}
                            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="promo-channel-combo">Promotion Channel</InputLabel>
                        <Autocomplete
                            multiple
                            disablePortal
                            id="promo-channel-combo"
                            size="small"
                            value={selectedChannels === null? null : selectedChannels}
                            options={channelList}
                            onChange={(event, newValue) => {
                                setSelectedChannels(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="storageLocation">Storage Location</InputLabel>
                        <TextField
                            fullWidth
                            {...register("storageLocation")}
                            inputProps={{maxLength: 255}}
                            id="storageLocation"
                            autoComplete="off"
                        />
                    </Grid>

                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5}}>
                        <InputLabel htmlFor="physicalAward">Physical Award</InputLabel>
                        <TextField
                            fullWidth
                            {...register("physicalAward")}
                            inputProps={{maxLength: 100}}
                            id="physicalAward"
                            autoComplete="off"
                        />
                    </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={eventFromError || eventToError || awardFromError || awardToError}
                                >
                                    Search
                                </Button>
                            </Grid>

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

                    <Grid item>
                        <Grid container>
                            {
                                ability.can('EDIT','AWARD') ?
                                    <Grid container>
                                        <Grid item sx={{ml:3, mr:1.5, mb:2}}>
                                            <Button
                                                variant="contained"
                                                color="create"
                                                onClick={createNewAward}>
                                                New Award
                                            </Button>
                                            <GeneralTwoComboWindow
                                                isWindowOpen={isWindowOpen}
                                                title={"New Award"}
                                                content={"Event"}
                                                content2={"Application"}
                                                comboList={eventList}
                                                comboList2={applicationList}
                                                setValueCallback={setSelectedEvent}
                                                setValueCallback2={setSelectedApplication}
                                                onNormalClose={handleClose}
                                                onConfirmClose={updateData}
                                            />
                                        </Grid>
                                            <Grid item sx={{ml: {xs: 1.5, md: 1.5, lg: 1.5}, mr: 1.5, mb: 2}}>
                                                {ability.can('MASS', 'IMPORT_AWARD') ?

                                                <ThemeProvider theme={LIONER_MEDIUM_BUTTON_THEME}>
                                                    <Button
                                                        variant="contained"
                                                        color="saveAs"
                                                        onClick={downloadTemplate}
                                                    >
                                                        Download Template
                                                    </Button>
                                                </ThemeProvider>
                                                    :
                                                    <></>
                                                }
                                            </Grid>

                                        {ability.can('MASS', 'IMPORT_AWARD') ?
                                            <Grid item sx={{ml: {xs: 3, md: 3, lg: 1.5}, mr: 3, mb: 2}}>
                                                <ThemeProvider theme={LIONER_MEDIUM_BUTTON_THEME}>
                                                    <input
                                                        type="file"
                                                        accept=".xlsx"
                                                        ref={fileInputRef}
                                                        style={{display: 'none'}}
                                                        onChange={handleFileInputChange}
                                                    />
                                                    <Button
                                                        variant="contained"
                                                        color="save"
                                                        onClick={handleImportTemplateClick}
                                                    >
                                                        Import Template
                                                    </Button>
                                                </ThemeProvider>
                                                <ImportResultWindow
                                                    isWindowOpen={isResultWindowOpen}
                                                    isMultiTable={true}
                                                    title={"Import Award Record Template Result"}
                                                    onNormalClose={handleWindowClose}
                                                    onConfirmClose={handleReload}
                                                    validateResult={importStatus}
                                                    isAppreciation={false}
                                                    eventCount={eventCount}
                                                    applicationCount={applicationCount}
                                                    awardCount={awardCount}
                                                    recordList={importErrorList}
                                                    status={importStatus}
                                                    setIsUploading={setIsUploading}
                                                    module={"Event"}
                                                />
                                            </Grid>
                                            : <></>
                                        }
                                    </Grid>

                                    :
                                    <Grid/>
                            }

                        </Grid>
                    </Grid>
                    </ThemeProvider>
                </Grid>
            </form>
            </Collapse>
        </MainCard>
    );
};

export default AwardSearchForm;
