// material-ui
import {
    Button,
    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 {ThemeProvider} from "@emotion/react";
import { useNavigate } from "react-router-dom";
import {PNSPS_BUTTON_THEME} from "../../../themes/buttonConst";

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 SearchPublicNoticeForm = ({ applySearch, searchCriteria, onGridReady}) => {
    const navigate = useNavigate()

    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(() => {
        // console.log(minDate)
        setFromDateValue(minDate);
    }, [minDate]);
    
    React.useEffect(() => {
        setToDateValue(maxDate);
    }, [maxDate]);

    const marginBottom = 2.5;
    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 = {
            key: data.key,
            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({key:""});
        localStorage.setItem('searchCriteria',"")
    }


    return (
        <MainCard xs={12} md={12} lg={12}
            border={false}
            content={false}
            sx={{ backgroundColor: '#fff' }}
        >

            <form onSubmit={handleSubmit(onSubmit)}>
                <Grid container sx={{ backgroundColor: '#ffffff', ml: 2, mt: 1, mb: marginBottom}} width="98%">
                    {/*row 1*/}
                    <Grid item justifyContent="space-between" alignItems="center" sx={{mt:1,ml:3,mb:marginBottom}}>
                        <Typography variant="pnspsFormHeader" >
                            Search
                        </Typography>
                    </Grid>
                    {/*row 2*/}
                    <Grid container display="flex" alignItems={"center"}>
                        <Grid item xs={12} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: marginBottom }}>
                            <TextField
                                fullWidth
                                {...register("key")}
                                id='key'
                                label={"Key"}
                                defaultValue={searchCriteria.key}
                                InputLabelProps={{
                                    shrink: true
                                }}
                            />
                        </Grid>

                        <Grid item xs={12} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:marginBottom}}>
                            <Grid container spacing={1}>
                                <Grid item xs={6}>
                                    <LocalizationProvider dateAdapter={AdapterDayjs}>
                                        <DemoItem  components={['DatePicker']}>
                                            <DatePicker
                                                id="dateFrom"
                                                // onError={(newError) => setReceiptFromError(newError)}
                                                slotProps={{
                                                    field: { readOnly: true, },
                                                    // textField: {
                                                    //     helperText: receiptFromErrorMessage,
                                                    // },
                                                }}
                                                format="DD/MM/YYYY"
                                                label={"Submit Date (From)"}
                                                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={6}>
                                    <LocalizationProvider dateAdapter={AdapterDayjs}>
                                        <DemoItem  components={['DatePicker']}>
                                            <DatePicker
                                                id="dateTo"
                                                // onError={(newError) => setReceiptFromError(newError)}
                                                slotProps={{
                                                    field: { readOnly: true, },
                                                    // textField: {
                                                    //     helperText: receiptFromErrorMessage,
                                                    // },
                                                }}
                                                format="DD/MM/YYYY"
                                                label={"Submit Date (To)"}
                                                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={{ ml: 3 }}>
                            <Button
                                variant="contained"
                                color="green"
                                onClick={()=>{
                                    navigate('/setting/announcement/details/' + 0);
                                }}
                            >
                                Create
                            </Button>
                        </Grid>
                        <Grid item sx={{ ml: 3 }}>
                            <Button
                                variant="contained"
                                color="cancel"
                                onClick={resetForm}
                            >
                                Reset
                            </Button>
                        </Grid>

                        <Grid item sx={{ ml: 3 }}>
                            <Button
                                variant="contained"
                                type="submit"
                                disabled={onGridReady}
                            >
                                Submit
                            </Button>
                        </Grid>
                        </ThemeProvider>
                    </Grid>
                </Grid>
            </form>
        </MainCard>
    );
};

export default SearchPublicNoticeForm;
