// material-ui
import {
    Button,
    Grid, InputLabel, Typography,
} from '@mui/material';
import MainCard from "../../components/MainCard";
import {useForm} from "react-hook-form";
import * as React from "react";
import {ThemeProvider} from "@emotion/react";
import {LIONER_BUTTON_THEME, GENERAL_RED_COLOR} from "../../themes/colorConst";
import {CARD_MAX_WIDTH} from "../../themes/themeConst";
import {useContext, useState} from "react";
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 {GET_APPRECIATION_CASES_REPORT} from "../../utils/ApiPathConst";
import axios from "axios";
import {apiPath} from "../../auth/utils";
import UploadContext from "../../components/UploadProvider";
// ==============================|| DASHBOARD - DEFAULT ||============================== //

const AppreciationGenerateForm = () => {
    const { setIsUploading } = useContext(UploadContext);

    const { handleSubmit } = useForm()
    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 shouldDisableDateTo = (date) => {
        // Disable dates with a different year or month than the selected date
        if (lnReceiptDateFrom && lnReceiptDateFrom.year() !== date.year()) {
            return true;
        }
        if (lnReceiptDateFrom && lnReceiptDateFrom.month() !== date.month()) {
            return true;
        }
        return false;
    };

    const shouldDisableDateFrom = (date) => {
        // Disable dates with a different year or month than the selected date
        if (lnReceiptDateTo && lnReceiptDateTo.year() !== date.year()) {
            return true;
        }
        if (lnReceiptDateTo && lnReceiptDateTo.month() !== date.month()) {
            return true;
        }
        return false;
    };

    function resetForm(){
        setLNReceiptDateFrom(null);
        setLNReceiptDateTo(null);
    }

    const onSubmit = () => {
        setIsUploading(true);
        axios.get(`${apiPath}${GET_APPRECIATION_CASES_REPORT}`,{
            responseType: 'blob',
            params:{
                dateFrom: dayjs(lnReceiptDateFrom).format('YYYY-MM-DD'),
                dateTo: dayjs(lnReceiptDateTo).format('YYYY-MM-DD')
            }
        })
            .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;
            });
    };

    return (
        <MainCard xs={12} md={12} lg={12}
                  content={false}
                  sx={{width:CARD_MAX_WIDTH}}
        >

            <form onSubmit={handleSubmit(onSubmit)}>
                {/*row 1*/}
                <Grid item justifyContent="space-between" alignItems="center" sx={{mt:2,ml:3,mb:1.5}}>
                    <Typography variant="lionerSubLabel" >
                        Search Criteria(s)
                    </Typography>
                </Grid>


                {/*row 2*/}
                <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5}}>
                    <InputLabel>
                        LN Receipt Date From
                        <Typography sx={{ color: GENERAL_RED_COLOR }} component="span">*</Typography>
                    </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"
                                        maxDate={lnReceiptDateTo === null ? null : dayjs(lnReceiptDateTo)}
                                        value={lnReceiptDateFrom === null ? null : dayjs(lnReceiptDateFrom)}
                                        onChange={(newValue) => setLNReceiptDateFrom(newValue)}
                                        shouldDisableDate={shouldDisableDateFrom}
                                    />
                                </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"
                                        minDate={lnReceiptDateFrom === null ? null : dayjs(lnReceiptDateFrom)}
                                        value={lnReceiptDateTo === null ? null : dayjs(lnReceiptDateTo)}
                                        onChange={(newValue) => setLNReceiptDateTo(newValue)}
                                        shouldDisableDate={shouldDisableDateTo}
                                    />
                                </DemoItem >
                            </LocalizationProvider>
                        </Grid>
                    </Grid>
                </Grid>


                {/*last row*/}
                <Grid container maxWidth justifyContent="flex-start" sx={{mt:2, mb:2}}>
                    <ThemeProvider theme={LIONER_BUTTON_THEME}>
                        <Grid item sx={{ml:3, mr:1.5, }}>
                            <Button
                                variant="contained"
                                type="submit"
                                color="export"
                                disabled={
                                    (lnReceiptDateFrom == null || lnReceiptDateTo == null) ||
                                    (lnReceiptDateFromError || lnReceiptDateToError)
                                }
                            >
                                Generate
                            </Button>
                        </Grid>

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

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

export default AppreciationGenerateForm;
