// 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} from "../../auth/utils";
import {
    GET_APPRECIATION_CATEGORY_COMBO_LIST,
    GET_APPRECIATION_EXPORT,
    GET_APPRECIATION_IMPORT_TEMPLATE,
    GET_SBU_DIVISION_COMBO_LIST,
    POST_APPRECIATION_IMPORT,
} from "../../utils/ApiPathConst";
import {LIONER_BUTTON_THEME, LIONER_MEDIUM_BUTTON_THEME} from "../../themes/colorConst";
import {
    getIdList, isOptionEqualToValue, notifyDeleteError
} 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 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 "./ImportResultWindow";
import {isObjEmpty} from "../../utils/Utils";

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

const AppreciationSearchForm = ({applySearch, setExpanded,expanded}) => {

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

    const [selectedDivisions, setSelectedDivisions] = useState([]);
    const [selectedCategories, setSelectedCategories] = useState([]);
    const [categoryList, setCategoryList] = useState([]);
    const [sbuDivisionList, setSBUDivisionList] = useState([]);
    const [recordCount, setRecordCount] = useState(0);
    const [importErrorList, setImportErrorList] = useState([]);
    const [importStatus, setImportStatus] = useState(0);

    const { reset, register, handleSubmit, getValues } = useForm()

    const [receiptDateFrom, setReceiptDateFrom] = useState(null);
    const [receiptDateTo, setReceiptDateTo] = useState(null);
    const [receiptFromError, setReceiptFromError] = React.useState(null);
    const [receiptToError, setReceiptToError] = React.useState(null);
    const receiptFromErrorMessage = React.useMemo(() => {
        switch (receiptFromError) {
            case 'invalidDate': {
                return "Invalid date";
            }
        }
    }, [receiptFromError]);
    const receiptToErrorMessage = React.useMemo(() => {
        switch (receiptToError) {
            case 'invalidDate': {
                return "Invalid date";
            }
        }
    }, [receiptToError]);

    const [lnReceiptDateFrom, setLNReceiptDateFrom] = useState(null);
    const [lnReceiptDateTo, setLNReceiptDateTo] = useState(null);
    const [lnReceiptDateFromError, setLNReceiptDateFromError] = React.useState(null);
    const [lnReceiptDateToError, setLNReceiptDateToError] = React.useState(null);
    const lnReceiptDateFromErrorMessage = React.useMemo(() => {
        switch (lnReceiptDateFromError) {
            case 'invalidDate': {
                return "Invalid date";
            }
        }
    }, [lnReceiptDateFromError]);
    const lnReceiptDateToErrorMessage = React.useMemo(() => {
        switch (lnReceiptDateToError) {
            case 'invalidDate': {
                return "Invalid date";
            }
        }
    }, [lnReceiptDateToError]);

    const [clientReplyDateFrom, setClientReplyDateFrom] = useState(null);
    const [clientReplyDateTo, setClientReplyDateTo] = useState(null);
    const [clientReplyDateFromError, setClientReplyDateFromError] = React.useState(null);
    const [clientReplyDateToError, setClientReplyDateToError] = React.useState(null);
    const clientReplyDateFromErrorMessage = React.useMemo(() => {
        switch (clientReplyDateFromError) {
            case 'invalidDate': {
                return "Invalid date";
            }
        }
    }, [clientReplyDateFromError]);
    const clientReplyDateToErrorMessage = React.useMemo(() => {
        switch (clientReplyDateToError) {
            case 'invalidDate': {
                return "Invalid date";
            }
        }
    }, [clientReplyDateToError]);

    const [staffReplyDateFrom, setStaffReplyDateFrom] = useState(null);
    const [staffReplyDateTo, setStaffReplyDateTo] = useState(null);
    const [staffReplyDateFromError, setStaffReplyDateFromError] = React.useState(null);
    const [staffReplyDateToError, setStaffReplyDateToError] = React.useState(null);
    const staffReplyDateFromErrorMessage = React.useMemo(() => {
        switch (staffReplyDateFromError) {
            case 'invalidDate': {
                return "Invalid date";
            }
        }
    }, [staffReplyDateFromError]);
    const staffReplyDateToErrorMessage = React.useMemo(() => {
        switch (staffReplyDateToError) {
            case 'invalidDate': {
                return "Invalid date";
            }
        }
    }, [staffReplyDateToError]);

    // ==============================|| IMPORT TEMPLATE WINDOW RELATED ||============================== //
    const fileInputRef = useRef(null);

    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_APPRECIATION_IMPORT}`,
                    formData,
                    {
                        headers: {
                            'Content-Type': 'multipart/form-data',
                        }
                    }
                )
                .then((response) => {
                    if (response.status === 200) {
                        setRecordCount(response.data.data.recordCount);
                        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 = {
            sbuIds: isObjEmpty(getIdList(selectedDivisions)) ? null : "[" + getIdList(selectedDivisions).toString() + "]" ,
            categoryIds: getIdList(selectedCategories),
            clientDepOrOrg: data.department,
            clientName: data.clientName,
            receiptDateFrom: receiptDateFrom === null ? null : dayjs(receiptDateFrom).format('YYYY-MM-DD'),
            receiptDateTo: receiptDateTo === null ? null : dayjs(receiptDateTo).format('YYYY-MM-DD'),
            lnReceiptDateFrom: lnReceiptDateFrom === null ? null : dayjs(lnReceiptDateFrom).format('YYYY-MM-DD'),
            lnReceiptDateTo: lnReceiptDateTo === null ? null : dayjs(lnReceiptDateTo).format('YYYY-MM-DD'),
            clientReplyDateFrom: clientReplyDateFrom === null ? null : dayjs(clientReplyDateFrom).format('YYYY-MM-DD'),
            clientReplyDateTo: clientReplyDateTo === null ? null : dayjs(clientReplyDateTo).format('YYYY-MM-DD'),
            staffReplyDateFrom: staffReplyDateFrom === null ? null : dayjs(staffReplyDateFrom).format('YYYY-MM-DD'),
            staffReplyDateTo: staffReplyDateTo === null ? null : dayjs(staffReplyDateTo).format('YYYY-MM-DD'),
        };

        applySearch(temp);
    }

    function displayImportResult(){
        setIsResultWindowOpen(true);
    }

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


    function downloadTemplate(){
        axios.get(`${apiPath}${GET_APPRECIATION_IMPORT_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;
            });
    }

    function newAppreciation(){
        navigate(`/appreciation/maintain/-1`);
    }


    const onSubmit = (data) => {
        const temp = {
            sbuIds: isObjEmpty(getIdList(selectedDivisions)) ? null : "[" + getIdList(selectedDivisions).toString() + "]" ,
            categoryIds: getIdList(selectedCategories),
            clientDepOrOrg: data.department,
            clientName: data.clientName,
            receiptDateFrom: receiptDateFrom === null ? null : dayjs(receiptDateFrom).format('YYYY-MM-DD'),
            receiptDateTo: receiptDateTo === null ? null : dayjs(receiptDateTo).format('YYYY-MM-DD'),
            lnReceiptDateFrom: lnReceiptDateFrom === null ? null : dayjs(lnReceiptDateFrom).format('YYYY-MM-DD'),
            lnReceiptDateTo: lnReceiptDateTo === null ? null : dayjs(lnReceiptDateTo).format('YYYY-MM-DD'),
            clientReplyDateFrom: clientReplyDateFrom === null ? null : dayjs(clientReplyDateFrom).format('YYYY-MM-DD'),
            clientReplyDateTo: clientReplyDateTo === null ? null : dayjs(clientReplyDateTo).format('YYYY-MM-DD'),
            staffReplyDateFrom: staffReplyDateFrom === null ? null : dayjs(staffReplyDateFrom).format('YYYY-MM-DD'),
            staffReplyDateTo: staffReplyDateTo === null ? null : dayjs(staffReplyDateTo).format('YYYY-MM-DD'),
        };
        applySearch(temp);
        setExpanded(false);
    };

    function onExport(){
        const data = getValues();
        const temp = {
            sbuIds: isObjEmpty(getIdList(selectedDivisions)) ? null : "[" + getIdList(selectedDivisions).toString() + "]" ,
            categoryIds: getIdList(selectedCategories),
            clientDepOrOrg: data.department,
            clientName: data.clientName,
            receiptDateFrom: receiptDateFrom === null ? null : dayjs(receiptDateFrom).format('YYYY-MM-DD'),
            receiptDateTo: receiptDateTo === null ? null : dayjs(receiptDateTo).format('YYYY-MM-DD'),
            lnReceiptDateFrom: lnReceiptDateFrom === null ? null : dayjs(lnReceiptDateFrom).format('YYYY-MM-DD'),
            lnReceiptDateTo: lnReceiptDateTo === null ? null : dayjs(lnReceiptDateTo).format('YYYY-MM-DD'),
            clientReplyDateFrom: clientReplyDateFrom === null ? null : dayjs(clientReplyDateFrom).format('YYYY-MM-DD'),
            clientReplyDateTo: clientReplyDateTo === null ? null : dayjs(clientReplyDateTo).format('YYYY-MM-DD'),
            staffReplyDateFrom: staffReplyDateFrom === null ? null : dayjs(staffReplyDateFrom).format('YYYY-MM-DD'),
            staffReplyDateTo: staffReplyDateTo === null ? null : dayjs(staffReplyDateTo).format('YYYY-MM-DD'),
        };
        setIsUploading(true);
        axios.get(`${apiPath}${GET_APPRECIATION_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", response.headers.filename);
                    link.click();
                }
            })
            .catch(error => {
                setIsUploading(false);
                console.log(error);
                return false;
            });
    }

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

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

    useEffect(() => {
        getDivisionCombo();
        getCategoryCombo();
    }, []);

    function resetForm(){
        setSelectedDivisions([]);
        setSelectedCategories([]);
        setReceiptDateFrom(null);
        setReceiptDateTo(null);
        setLNReceiptDateFrom(null);
        setLNReceiptDateTo(null);
        setClientReplyDateFrom(null);
        setClientReplyDateTo(null);
        setStaffReplyDateFrom(null);
        setStaffReplyDateTo(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="division-combo">SBU / Division</InputLabel>
                        <Autocomplete
                            multiple
                            disablePortal
                            id="division-combo"
                            size="small"
                            value={selectedDivisions === null? null : selectedDivisions}
                            options={sbuDivisionList}
                            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="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>Receipt 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="receiptDateFrom"
                                            onError={(newError) => setReceiptFromError(newError)}
                                            slotProps={{
                                                field: { clearable: true },
                                                textField: {
                                                    helperText: receiptFromErrorMessage,
                                                },
                                            }}
                                            format="DD/MM/YYYY"
                                            value={receiptDateFrom === null ? null : dayjs(receiptDateFrom)}
                                            onChange={(newValue) => setReceiptDateFrom(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) => setReceiptToError(newError)}
                                            slotProps={{
                                                field: { clearable: true },
                                                textField: {
                                                    helperText: receiptToErrorMessage,
                                                },
                                            }}
                                            format="DD/MM/YYYY"
                                            //label="To Date"
                                            value={receiptDateTo === null ? null : dayjs(receiptDateTo)}
                                            onChange={(newValue) => setReceiptDateTo(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>LN Receipt 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="lnReceiptDateFrom"
                                            onError={(newError) => setLNReceiptDateFromError(newError)}
                                            slotProps={{
                                                field: { clearable: true },
                                                textField: {
                                                    helperText: lnReceiptDateFromErrorMessage,
                                                },
                                            }}
                                            format="DD/MM/YYYY"
                                            value={lnReceiptDateFrom === null ? null : dayjs(lnReceiptDateFrom)}
                                            onChange={(newValue) => setLNReceiptDateFrom(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="lnReceiptDateTo"
                                            onError={(newError) => setLNReceiptDateToError(newError)}
                                            slotProps={{
                                                field: { clearable: true },
                                                textField: {
                                                    helperText: lnReceiptDateToErrorMessage,
                                                },
                                            }}
                                            format="DD/MM/YYYY"
                                            //label="To Date"
                                            value={lnReceiptDateTo === null ? null : dayjs(lnReceiptDateTo)}
                                            onChange={(newValue) => setLNReceiptDateTo(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="department">Client Department / Organization</InputLabel>
                        <TextField
                            fullWidth
                            {...register("department")}
                            inputProps={{maxLength: 255}}
                            id='department'
                            autoComplete="off"
                        />
                    </Grid>

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

                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5}}>
                        <InputLabel>Client Reply 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="clientReplyDateFrom"
                                            onError={(newError) => setClientReplyDateFromError(newError)}
                                            slotProps={{
                                                field: { clearable: true },
                                                textField: {
                                                    helperText: clientReplyDateFromErrorMessage,
                                                },
                                            }}
                                            format="DD/MM/YYYY"
                                            value={clientReplyDateFrom === null ? null : dayjs(clientReplyDateFrom)}
                                            onChange={(newValue) => setClientReplyDateFrom(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="clientReplyDateTo"
                                            onError={(newError) => setClientReplyDateToError(newError)}
                                            slotProps={{
                                                field: { clearable: true },
                                                textField: {
                                                    helperText: clientReplyDateToErrorMessage,
                                                },
                                            }}
                                            format="DD/MM/YYYY"
                                            //label="To Date"
                                            value={clientReplyDateTo === null ? null : dayjs(clientReplyDateTo)}
                                            onChange={(newValue) => setClientReplyDateTo(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>Staff Reply 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="staffReplyDateFrom"
                                            onError={(newError) => setStaffReplyDateFromError(newError)}
                                            slotProps={{
                                                field: { clearable: true },
                                                textField: {
                                                    helperText: staffReplyDateFromErrorMessage,
                                                },
                                            }}
                                            format="DD/MM/YYYY"
                                            value={staffReplyDateFrom === null ? null : dayjs(staffReplyDateFrom)}
                                            onChange={(newValue) => setStaffReplyDateFrom(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="staffReplyDateTo"
                                            onError={(newError) => setStaffReplyDateToError(newError)}
                                            slotProps={{
                                                field: { clearable: true },
                                                textField: {
                                                    helperText: staffReplyDateToErrorMessage,
                                                },
                                            }}
                                            format="DD/MM/YYYY"
                                            //label="To Date"
                                            value={staffReplyDateTo === null ? null : dayjs(staffReplyDateTo)}
                                            onChange={(newValue) => setStaffReplyDateTo(newValue)}
                                        />
                                    </DemoItem >
                                </LocalizationProvider>
                            </Grid>
                        </Grid>
                    </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={
                                        receiptFromError || receiptToError ||
                                        lnReceiptDateFromError || lnReceiptDateToError ||
                                        clientReplyDateFromError || clientReplyDateToError ||
                                        staffReplyDateFromError || staffReplyDateFromError
                                    }
                                >
                                    Search
                                </Button>
                            </Grid>

                            <Grid item sx={{ml:1.5, mr:1.5, mb:2}}>
                                <Button
                                    variant="contained"
                                    color="export"
                                    onClick={onExport}
                                    disabled={
                                        receiptFromError || receiptToError ||
                                        lnReceiptDateFromError || lnReceiptDateToError ||
                                        clientReplyDateFromError || clientReplyDateToError ||
                                        staffReplyDateFromError || staffReplyDateFromError
                                    }
                                >
                                    Export
                                </Button>
                            </Grid>

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


                        </Grid>
                    </Grid>

                    <Grid item>
                        {
                            ability.can('MAINTAIN','APPRECIATION') ?
                                <Grid container>
                                    <Grid item sx={{ml:{xs:3, md:3, lg:1.5}, mr:1.5, mb:2}}>
                                        <ThemeProvider theme={LIONER_MEDIUM_BUTTON_THEME}>
                                            <Button
                                                variant="contained"
                                                color="create"
                                                onClick={newAppreciation}
                                            >
                                                New Appreciation
                                            </Button>
                                        </ThemeProvider>
                                    </Grid>

                                    <Grid item sx={{ml:{xs:1.5, md:1.5, lg:1.5}, mr:1.5, mb:2}}>
                                        <ThemeProvider theme={LIONER_MEDIUM_BUTTON_THEME}>
                                            <Button
                                                variant="contained"
                                                color="saveAs"
                                                onClick={downloadTemplate}
                                            >
                                                Download Template
                                            </Button>
                                        </ThemeProvider>
                                    </Grid>

                                    <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={false}
                                            title={"Import Appreciation Record Template Result"}
                                            onNormalClose={handleWindowClose}
                                            onConfirmClose={handleReload}
                                            validateResult={importStatus}                                            
                                            isAppreciation={true}
                                            recordCount={recordCount}
                                            recordList={importErrorList}
                                            status={importStatus}
                                            setIsUploading={setIsUploading}
                                            module={"Event"}
                                        />
                                    </Grid>

                                </Grid>
                                :
                                <Grid/>
                        }

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

export default AppreciationSearchForm;
