// material-ui
import {
    Button,
    Grid, 
    TextField,
    Autocomplete,
    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 * as ComboData from "utils/ComboData";
import * as DateUtils from "utils/DateUtils";
import * as ComboData from "utils/ComboData";

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, generateXML, searchCriteria, onGridReady, selectedIds = [] }) => {

    // const [minDate, setMinDate] = React.useState(searchCriteria.dateFrom);
    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");
    const [payMethod, setPayMethod] = React.useState(ComboData.payMethod[0]);
    // const [status, setStatus] = React.useState(ComboData.paymentStatus[0]);
    const marginBottom = 2.5;

    const {
        register, 
        handleSubmit, 
    } = useForm()

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

    const toPayMethodArray = (opt) => {
    if (!opt || opt.type === 'all') return [];
    return Array.isArray(opt.type) ? opt.type : [opt.type];
    };

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

        if (fromDateValue != "dd / mm / yyyy") {
            sentDateFrom = DateUtils.dateValue(fromDateValue)
        }
        if (toDateValue != "dd / mm / yyyy") {
            sentDateTo = DateUtils.dateValue(toDateValue)
        }
        
        const temp = {
            // code: data.code,
            // transNo: data.transNo,
            dateFrom: sentDateFrom,
            dateTo: sentDateTo,
            // paymentId: selectedIds.join(','),
            payMethod : toPayMethodArray(payMethod),
            // status : (status?.type && status?.type != 'all') ? status?.type : "",
        };
        applySearch(temp);
    };

    const generateHandler = () => {
        if (!selectedIds || selectedIds.length === 0) {
            alert('No payment is selected.');
            return;
        }

        let sentDateFrom = "";
        let sentDateTo = "";

        if (fromDateValue !== "dd / mm / yyyy") {
            sentDateFrom = DateUtils.dateValue(fromDateValue);
        }
        if (toDateValue !== "dd / mm / yyyy") {
            sentDateTo = DateUtils.dateValue(toDateValue);
        }

        const temp = {
            dateFrom: sentDateFrom,
            dateTo: sentDateTo,
        };

        generateXML(temp);
    };



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

            <form onSubmit={handleSubmit(onSubmit)} >
                <Grid container sx={{ backgroundColor: '#ffffff', ml: 2, mt: 1}} width="98%">
                    {/*row 1*/}
                    <Grid item justifyContent="space-between" alignItems="center" sx={{mt:1,ml:3,mb:2.5}}>
                        <Typography variant="h5" >
                            Credit Date
                        </Typography>
                    </Grid>
                    {/*row 2*/}

                    <Grid container display="flex" alignItems={"center"}>
                        <Grid item xs={9} s={6} md={3} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>                 
                            <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="From Date"
                                        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={9} s={6} md={3} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
                            <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="To Date"
                                        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 item xs={9} s={6} md={3} lg={3} sx={{ ml: 3, mr: 3, mb: marginBottom }}>
                                <Autocomplete
                                    {...register("payMethod")}
                                    disablePortal={false}
                                    size="small"
                                    id="payMethod"
                                    filterOptions={(options) => options}
                                    options={ComboData.payMethod}
                                    value={payMethod}
                                    getOptionLabel={(option) => (option?.label != null ? String(option.label) : "")}
                                    inputValue={payMethod?.label ? payMethod?.label : ""}
                                    onChange={(event, newValue) => {
                                        if(newValue==null){
                                            setPayMethod(ComboData.payMethod[0]);
                                        }else{
                                            setPayMethod(newValue);
                                        }
                                    }}
                                    sx={{
                                        '& .MuiInputBase-root': { alignItems: 'center' },
                                        '& .MuiAutocomplete-endAdornment': { top: '50%', transform: 'translateY(-50%)' },
                                        '& .MuiOutlinedInput-root': { height: 40 }
                                    }}
                                    renderInput={(params) => (
                                        <TextField {...params}
                                            label="Payment Method"
                                            InputLabelProps={{ shrink: true }}
                                        />
                                    )}
                                />
                        </Grid>

                        {/* <Grid item xs={9} s={6} md={4} lg={3}>
                        </Grid> */}
                    </Grid>

                    <Grid container justifyContent="flex-end" direction="row"  alignItems="center" spacing={3} sx={{ ml: 3, mr: 3, mb: 3, }}>
                        <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                        <Grid item  >
                            <Button
                                variant="contained"
                                type="submit"
                                disabled={onGridReady}
                            >
                                Search
                            </Button>
                        </Grid>

                        <Grid item  >
                            <Button
                                variant="contained"
                                onClick={generateHandler}
                                disabled={!selectedIds || selectedIds.length === 0}
                                >
                                Generate
                            </Button>

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

export default SearchPublicNoticeForm;
