// material-ui
import {
    Button,
    CardContent,
    Grid, TextField,
    Typography
} from '@mui/material';
import MainCard from "components/MainCard";
import { useForm } from "react-hook-form";
import * as React from "react";
import * as DateUtils from "utils/DateUtils";
import {PNSPS_BUTTON_THEME} from "../../../themes/buttonConst";
import {ThemeProvider} from "@emotion/react";
import {FormattedMessage, useIntl} from "react-intl";

import {DatePicker} from "@mui/x-date-pickers/DatePicker";
import dayjs from "dayjs";
import {DemoItem} from "@mui/x-date-pickers/internals/demo";
import {LocalizationProvider} from "@mui/x-date-pickers/LocalizationProvider";
import {AdapterDayjs} from "@mui/x-date-pickers/AdapterDayjs";
// ==============================|| DASHBOARD - DEFAULT ||============================== //


const SearchForm = ({ applySearch, searchCriteria, onGridReady }) => {
    const intl = useIntl();
    const [minDate, setMinDate] = React.useState(searchCriteria.dateFrom);
    const [maxDate, setMaxDate] = React.useState(searchCriteria.dateTo);

    const [fromDateValue, setFromDateValue] = React.useState("dd / mm / yyyy");
    const [toDateValue, setToDateValue] = React.useState("dd / mm / yyyy");

    React.useEffect(() => {
        setFromDateValue(minDate);
    }, [minDate]);

    React.useEffect(() => {
        setToDateValue(maxDate);
    }, [maxDate]);

    const _sx = {
        padding: "4 2 4 2",
        boxShadow: 1,
        border: 1,
        borderColor: '#DDD',
        '& .MuiDataGrid-cell': {
            borderTop: 1,
            borderBottom: 1,
            borderColor: "#EEE"
        },
        '& .MuiDataGrid-footerContainer': {
            border: 1,
            borderColor: "#EEE"
        }
    }

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

    const onSubmit = (data) => {
        let sentDateFrom = "";
        let sentDateTo = "";

        if (fromDateValue != "dd / mm / yyyy" && toDateValue != "dd / mm / yyyy") {
            sentDateFrom = DateUtils.dateValue(fromDateValue)
            sentDateTo = DateUtils.dateValue(toDateValue)
        }
        const temp = {
            keyword: data.keyword,
            dateFrom: sentDateFrom,
            dateTo: sentDateTo,
            start:0,
            limit:10
        };
        applySearch(temp);
    };

    function resetForm() {
        setMinDate(DateUtils.dateValue(new Date().setDate(new Date().getDate()-14)))
        setMaxDate(DateUtils.dateValue(new Date()))
        reset();
        localStorage.setItem('searchCriteria',"")

    }


    return (
        <MainCard xs={12} md={12} lg={12}
            border={false}
            content={false}
            sx={_sx}
            >

            <form onSubmit={handleSubmit(onSubmit)}>
                {/*row 1*/}
                <CardContent sx={{ px: 2.5, pt: 3 }}>
                    <Grid item justifyContent="space-between" alignItems="center" >
                        <Typography variant="pnspsFormHeader">
                            <FormattedMessage id="searchForm"/>
                        </Typography>
                    </Grid>
                </CardContent>

                {/*row 2*/}
                <Grid container alignItems={"center"}>

                    <Grid item xs={12} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
                        <TextField
                            fullWidth
                            {...register("keyword")}
                            id='keyword'
                            aria-label={intl.formatMessage({id: 'keyword'})}
                            label={intl.formatMessage({id: 'keyword'}) + ":"}
                            defaultValue={searchCriteria.code}
                            InputLabelProps={{
                                shrink: true
                            }}
                        />
                    </Grid>

                    <Grid item xs={12} s={6} md={6} lg={4} sx={{ ml: 3, mr: 3, mb: 3 }}>
                        <Grid container>
                            <Grid item xs={5.25} s={5.25} md={5.25} lg={5.5}>
                                <LocalizationProvider dateAdapter={AdapterDayjs} localeText={DateUtils.getPickerLocaleText(intl.locale)}>
                                    <DemoItem  components={['DatePicker']}>
                                        <DatePicker
                                            id="dateFrom"
                                            // onError={(newError) => setReceiptFromError(newError)}
                                            slotProps={{
                                                field: { readOnly: true, },
                                                // textField: {
                                                //     helperText: receiptFromErrorMessage,
                                                // },
                                            }}
                                            format="DD/MM/YYYY"
                                            aria-label={intl.formatMessage({id: 'dateFrom'})}
                                            label={intl.formatMessage({id: 'dateFrom'})}
                                            value={minDate === null ? null : dayjs(minDate)}
                                            maxDate={maxDate === null ? null : dayjs(maxDate)}
                                            onChange={(newValue) => {
                                                // console.log(newValue)
                                                if(newValue!=null){
                                                    setMinDate(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'}}>
                                <FormattedMessage id="to" />
                            </Grid>

                            <Grid item xs={5.25} s={5.25} md={5.25} lg={5.5}>
                                <LocalizationProvider dateAdapter={AdapterDayjs} localeText={DateUtils.getPickerLocaleText(intl.locale)}>
                                    <DemoItem  components={['DatePicker']}>
                                        <DatePicker
                                            id="dateTo"
                                            // onError={(newError) => setReceiptFromError(newError)}
                                            slotProps={{
                                                field: { readOnly: true, },
                                                // textField: {
                                                //     helperText: receiptFromErrorMessage,
                                                // },
                                            }}
                                            format="DD/MM/YYYY"
                                            aria-label={intl.formatMessage({id: 'dateTo'})}
                                            value={maxDate === null ? null : dayjs(maxDate)}
                                            minDate={minDate === null ? null : dayjs(minDate)}
                                            onChange={(newValue) => {
                                                // console.log(newValue)
                                                if(newValue!=null){
                                                    setMaxDate(newValue);
                                                }
                                            }}
                                        />
                                    </DemoItem >
                                </LocalizationProvider>
                            </Grid>
                        </Grid>
                    </Grid>

                </Grid>


                {/*last row*/}
                <Grid container maxWidth justifyContent="flex-end">
                    <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                    <Grid item sx={{mr: 3, mb: 3 }}>
                        <Button
                            variant="contained"
                            color="cancel"
                            onClick={resetForm}
                            aria-label={intl.formatMessage({id: 'reset'})}
                        >
                            <FormattedMessage id="reset"/>
                        </Button>
                    </Grid>

                    <Grid item sx={{ ml: 3, mr: 3, mb: 3 }}>
                        <Button
                            variant="contained"
                            type="submit"
                            disabled={onGridReady}
                            aria-label={intl.formatMessage({id: 'submit'})}
                        >
                            <FormattedMessage id="submit"/>
                        </Button>
                    </Grid>
                    </ThemeProvider>
                </Grid>
            </form>
        </MainCard>
    );
};

export default SearchForm;
