// 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 Loadable from 'components/Loadable';
// const LoadingComponent = Loadable(React.lazy(() => import('pages/extra-pages/LoadingComponent')));

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, generateReport, onLoad }) => {

    const [sysTxnMinDate, setSysTxnMinDate] = React.useState(null);
    const [sysTxnMaxDate, setsysTxnMaxDate] = React.useState(null);
    const [txnMinDate, setTxnMinDate] = React.useState(null);
    const [txnMaxDate, setTxnMaxDate] = React.useState(null);
    const [collMinDate, setCollMinDate] = React.useState(null);
    const [collMaxDate, setCollMaxDate] = React.useState(null);

    const [sysTxnFromDateValue, setSysTxnFromDateValue] = React.useState(null);
    const [sysTxnToDateValue, setSysTxnToDateValue] = React.useState(null);
    const [txnFromDateValue, setTxnFromDateValue] = React.useState(null);
    const [txnToDateValue, setTxnToDateValue] = React.useState(null);
    const [collFromDateValue, setCollFromDateValue] = React.useState(null);
    const [collToDateValue, setCollToDateValue] = React.useState(null);
    
    const [status, setStatus] = React.useState(ComboData.paymentStatus[0]);
    const [method, setMethod] = React.useState(ComboData.paymentMethod[0]);
    const marginBottom = 2.5;

    const { register, handleSubmit } = useForm()

    React.useEffect(() => {
        setSysTxnFromDateValue(sysTxnMinDate);
    }, [sysTxnMinDate]);

    React.useEffect(() => {
        setSysTxnToDateValue(sysTxnMaxDate);
    }, [sysTxnMaxDate]);

    React.useEffect(() => {
        setTxnFromDateValue(txnMinDate);
    }, [txnMinDate]);

    React.useEffect(() => {
        setTxnToDateValue(txnMaxDate);
    }, [txnMaxDate]);

    React.useEffect(() => {
        setCollFromDateValue(collMinDate);
    }, [collMinDate]);

    React.useEffect(() => {
        setCollToDateValue(collMaxDate);
    }, [collMaxDate]);

    const onSubmit = () => {

        let sentSysTxnDateFrom = "";
        let sentSysTxnDateTo = "";
        let sentTxnDateFrom = "";
        let sentTxnDateTo = "";
        let sentCollDateFrom = "";
        let sentCollDateTo = "";
        // Invalid Date
        if (sysTxnFromDateValue != "dd / mm / yyyy" && sysTxnToDateValue != "dd / mm / yyyy" ) {
            sentSysTxnDateFrom = DateUtils.dateValue(sysTxnFromDateValue)!="Invalid Date"?DateUtils.dateValue(sysTxnFromDateValue):""
            sentSysTxnDateTo = DateUtils.dateValue(sysTxnToDateValue)!="Invalid Date"?DateUtils.dateValue(sysTxnToDateValue):""
        }
        if (txnFromDateValue != "dd / mm / yyyy" && txnToDateValue != "dd / mm / yyyy") {
            sentTxnDateFrom = DateUtils.dateValue(txnFromDateValue)!="Invalid Date"?DateUtils.dateValue(txnFromDateValue):""
            sentTxnDateTo = DateUtils.dateValue(txnToDateValue)!="Invalid Date"?DateUtils.dateValue(txnToDateValue):""
        }
        if (collFromDateValue != "dd / mm / yyyy" && collToDateValue != "dd / mm / yyyy") {
            sentCollDateFrom = DateUtils.dateValue(collFromDateValue)!="Invalid Date"?DateUtils.dateValue(collFromDateValue):""
            sentCollDateTo = DateUtils.dateValue(collToDateValue)!="Invalid Date"?DateUtils.dateValue(collToDateValue):""
        }

        const temp = {
            PaymentMethod:(method?.type && method?.type != 'Please Select') ? method?.type : "",
            PaymentStatus : (status?.type && status?.type != 'all') ? status?.type : "",
            SysTxnDateFrom: sentSysTxnDateFrom,
            SysTxnDateTo: sentSysTxnDateTo,
            TxnDateFrom: sentTxnDateFrom,
            TxnDateTo: sentTxnDateTo,
            CollDateFrom: sentCollDateFrom,
            CollDateTo: sentCollDateTo,
        };

        // console.log(temp)
        applySearch(temp);
    };

    const generateFileHandler = (fileFormart) => () => {
        let sentSysTxnDateFrom = "";
        let sentSysTxnDateTo = "";
        let sentTxnDateFrom = "";
        let sentTxnDateTo = "";
        let sentCollDateFrom = "";
        let sentCollDateTo = "";

        if (sysTxnFromDateValue != "dd / mm / yyyy" && sysTxnToDateValue != "dd / mm / yyyy" ) {
            sentSysTxnDateFrom = DateUtils.dateValue(sysTxnFromDateValue)!="Invalid Date"?DateUtils.dateValue(sysTxnFromDateValue):""
            sentSysTxnDateTo = DateUtils.dateValue(sysTxnToDateValue)!="Invalid Date"?DateUtils.dateValue(sysTxnToDateValue):""
        }
        if (txnFromDateValue != "dd / mm / yyyy" && txnToDateValue != "dd / mm / yyyy") {
            sentTxnDateFrom = DateUtils.dateValue(txnFromDateValue)!="Invalid Date"?DateUtils.dateValue(txnFromDateValue):""
            sentTxnDateTo = DateUtils.dateValue(txnToDateValue)!="Invalid Date"?DateUtils.dateValue(txnToDateValue):""
        }
        if (collFromDateValue != "dd / mm / yyyy" && collToDateValue != "dd / mm / yyyy") {
            sentCollDateFrom = DateUtils.dateValue(collFromDateValue)!="Invalid Date"?DateUtils.dateValue(collFromDateValue):""
            sentCollDateTo = DateUtils.dateValue(collToDateValue)!="Invalid Date"?DateUtils.dateValue(collToDateValue):""
        }

        const temp = {
            PaymentMethod:(method?.type && method?.type != 'Please Select') ? method?.type : "",
            PaymentStatus : (status?.type && status?.type != 'all') ? status?.type : "",
            SysTxnDateFrom: sentSysTxnDateFrom,
            SysTxnDateTo: sentSysTxnDateTo,
            TxnDateFrom: sentTxnDateFrom,
            TxnDateTo: sentTxnDateTo,
            CollDateFrom: sentCollDateFrom,
            CollDateTo: sentCollDateTo,
            ReportFormat:fileFormart
        };
        generateReport(temp);
    }

    const clearHandler = () => () => {
        setSysTxnMinDate(null)
        setsysTxnMaxDate(null)
        setTxnMinDate(null)
        setTxnMaxDate(null)
        setCollMinDate(null)
        setCollMaxDate(null)
        setSysTxnFromDateValue("")
        setSysTxnToDateValue("")
        setTxnFromDateValue("")
        setTxnToDateValue("")
        setCollFromDateValue("")
        setCollToDateValue("")
        setStatus(ComboData.paymentStatus[0])
        setMethod(ComboData.paymentMethod[0])
    }

    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" >
                          Submit Form
                        </Typography>
                    </Grid>

                    {/*row 2*/}

                    <Grid item xs={12} s={12} md={12} lg={12} sx={{ ml: 3, mr: 3, mb: marginBottom }}>
                       <Grid container spacing={3}>
                        <Grid item xs={9} s={9} md={3} lg={3} >
                            <Autocomplete
                                {...register("paymentMethod")}
                                disablePortal={false}
                                size="small"
                                id="paymentMethod"
                                filterOptions={(options) => options}
                                options={ComboData.paymentMethod}
                                value={method}
                                getOptionLabel={(option) => (option?.label != null ? String(option.label) : "")}
                                inputValue={method?.label ? method?.label : ""}
                                onChange={(event, newValue) => {
                                    if (newValue !== null) {
                                        setMethod(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={9} md={3} lg={3} >
                            <Autocomplete
                                {...register("status")}
                                disablePortal={false}
                                size="small"
                                id="status"
                                filterOptions={(options) => options}
                                options={ComboData.paymentStatus}
                                value={status}
                                getOptionLabel={(option) => (option?.label != null ? String(option.label) : "")}
                                inputValue={status?.label ? status?.label : ""}
                                onChange={(event, newValue) => {
                                    if (newValue !== null) {
                                        setStatus(newValue);
                                    }
                                }}
                                sx={{
                                    '& .MuiInputBase-root': { alignItems: 'center' },
                                    '& .MuiAutocomplete-endAdornment': { top: '50%', transform: 'translateY(-50%)' },
                                    '& .MuiOutlinedInput-root': { height: 40 }
                                }}
                                renderInput={(params) => (
                                    <TextField {...params}
                                        label="Payment Status"
                                        InputLabelProps={{ shrink: true }}
                                    />
                                )}
                            />
                        </Grid>
                       
                       </Grid>
                    </Grid>

                    <Grid container display="flex" alignItems={"center"}>
                        <Grid item xs={12} s={12} md={12} lg={12} sx={{ml:3, mr:3, mb:marginBottom}}>
                            <Grid container spacing={1}>
                                <Grid item xs={4}>                       
                                    <LocalizationProvider dateAdapter={AdapterDayjs}>
                                        <DemoItem  components={['DatePicker']}>
                                            <DatePicker
                                                id="sysTxnDateFrom"
                                                // onError={(newError) => setReceiptFromError(newError)}
                                                slotProps={{
                                                    field: { readOnly: true, },
                                                    textField: {
                                                        // helperText: receiptFromErrorMessage,
                                                        InputLabelProps: { shrink: true }
                                                    },
                                                }}
                                                format="DD/MM/YYYY"
                                                label="PNSPS Payment Date (From)"
                                                value={sysTxnMinDate === null ? null : dayjs(sysTxnMinDate)}
                                                maxDate={sysTxnMaxDate === null ? null : dayjs(sysTxnMaxDate)}
                                                onChange={(newValue) => {
                                                    setSysTxnMinDate(newValue);
                                                }}
                                            />
                                        </DemoItem >
                                    </LocalizationProvider>
                                </Grid>
                                <Grid item xs={4}>
                                    <LocalizationProvider dateAdapter={AdapterDayjs}>
                                        <DemoItem  components={['DatePicker']}>
                                            <DatePicker
                                                id="sysTxnDateTo"
                                                // onError={(newError) => setReceiptFromError(newError)}
                                                slotProps={{
                                                    field: { readOnly: true, },
                                                    textField: {
                                                        // helperText: receiptFromErrorMessage,
                                                        InputLabelProps: { shrink: true }
                                                    },
                                                }}
                                                format="DD/MM/YYYY"
                                                label="PNSPS Payment Date (To)"
                                                value={sysTxnMaxDate === null ? null : dayjs(sysTxnMaxDate)}
                                                minDate={sysTxnMinDate === null ? null : dayjs(sysTxnMinDate)}
                                                onChange={(newValue) => {
                                                    // console.log(newValue)
                                                    setsysTxnMaxDate(newValue);
                                                }}
                                            />
                                        </DemoItem >
                                    </LocalizationProvider>
                                </Grid>
                            </Grid>
                        </Grid>
                    </Grid>

                    {/*row 3*/}
                    <Grid container display="flex" alignItems={"center"}>
                        <Grid item xs={12} s={12} md={12} lg={12} sx={{ml:3, mr:3, mb:marginBottom}}>
                            <Grid container spacing={1}>
                                <Grid item xs={4}>                       
                                    <LocalizationProvider dateAdapter={AdapterDayjs}>
                                        <DemoItem  components={['DatePicker']}>
                                            <DatePicker
                                                id="txnDateFrom"
                                                // onError={(newError) => setReceiptFromError(newError)}
                                                slotProps={{
                                                    field: { readOnly: true, },
                                                    textField: {
                                                        // helperText: receiptFromErrorMessage,
                                                        InputLabelProps: { shrink: true }
                                                    },
                                                }}
                                                format="DD/MM/YYYY"
                                                label="FI Transaction Date (From)"
                                                value={txnMinDate === null ? null : dayjs(txnMinDate)}
                                                maxDate={txnMaxDate === null ? null : dayjs(txnMaxDate)}
                                                onChange={(newValue) => {
                                                    // console.log(newValue)
                                                    setTxnMinDate(newValue);
                                                }}
                                            />
                                        </DemoItem >
                                    </LocalizationProvider>
                                </Grid>
                                <Grid item xs={4}>
                                    <LocalizationProvider dateAdapter={AdapterDayjs}>
                                        <DemoItem  components={['DatePicker']}>
                                            <DatePicker
                                                id="txnDateTo"
                                                // onError={(newError) => setReceiptFromError(newError)}
                                                slotProps={{
                                                    field: { readOnly: true, },
                                                    textField: {
                                                        // helperText: receiptFromErrorMessage,
                                                        InputLabelProps: { shrink: true }
                                                    },
                                                }}
                                                format="DD/MM/YYYY"
                                                label="FI Transaction Date (To)"
                                                value={txnMaxDate === null ? null : dayjs(txnMaxDate)}
                                                minDate={txnMinDate === null ? null : dayjs(txnMinDate)}
                                                onChange={(newValue) => {
                                                    // console.log(newValue)
                                                    setTxnMaxDate(newValue);
                                                }}
                                            />
                                        </DemoItem >
                                    </LocalizationProvider>
                                </Grid>
                            </Grid>
                        </Grid>
                    </Grid>

                    {/*row 5*/}
                    <Grid container display="flex" alignItems={"center"}>
                        <Grid item xs={12} s={12} md={12} lg={12} sx={{ml:3, mr:3, mb:marginBottom}}>
                            <Grid container spacing={1}>
                                <Grid item xs={4}>                       
                                    <LocalizationProvider dateAdapter={AdapterDayjs}>
                                        <DemoItem  components={['DatePicker']}>
                                            <DatePicker
                                                id="collDateFrom"
                                                // onError={(newError) => setReceiptFromError(newError)}
                                                slotProps={{
                                                    field: { readOnly: true, },
                                                    textField: {
                                                        // helperText: receiptFromErrorMessage,
                                                        InputLabelProps: { shrink: true }
                                                    },
                                                }}
                                                format="DD/MM/YYYY"
                                                label="Bank Credit Date (From)"
                                                value={collMinDate === null ? null : dayjs(collMinDate)}
                                                maxDate={collMaxDate === null ? null : dayjs(collMaxDate)}
                                                onChange={(newValue) => {
                                                    // console.log(newValue)
                                                    setCollMinDate(newValue);
                                                }}
                                            />
                                        </DemoItem >
                                    </LocalizationProvider>
                                </Grid>
                                <Grid item xs={4}>
                                    <LocalizationProvider dateAdapter={AdapterDayjs}>
                                        <DemoItem  components={['DatePicker']}>
                                            <DatePicker
                                                id="collDateTo"
                                                // onError={(newError) => setReceiptFromError(newError)}
                                                slotProps={{
                                                    field: { readOnly: true, },
                                                    textField: {
                                                        // helperText: receiptFromErrorMessage,
                                                        InputLabelProps: { shrink: true }
                                                    },
                                                }}
                                                format="DD/MM/YYYY"
                                                label="Bank Credit Date (To)"
                                                value={collMaxDate === null ? null : dayjs(collMaxDate)}
                                                minDate={collMinDate === null ? null : dayjs(collMinDate)}
                                                onChange={(newValue) => {
                                                    // console.log(newValue)
                                                    setCollMaxDate(newValue);
                                                }}
                                            />
                                        </DemoItem >
                                    </LocalizationProvider>
                                </Grid>
                            </Grid>
                        </Grid>
                    </Grid>
                    <Grid container direction="row" justifyContent="space-between">
                        <Grid item>
                            <Grid container justifyContent="flex-Start" direction="row"  alignItems="center" spacing={3}>
                                <Grid item sx={{ ml: 3, mb: 3, }} >
                                    {/* <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                                        <Button
                                            variant="contained"
                                            color="cancel"
                                            onClick={clearHandler()}
                                        >
                                            Reset
                                        </Button>    
                                    </ThemeProvider> */}
                                </Grid>
                            </Grid>
                        </Grid>
                        <Grid item>
                            <Grid container justifyContent="flex-end" direction="row"  alignItems="center" spacing={3}>
                                <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                                    <Grid item sx={{ mr: 3, mb: 3, }} >
                                        <Button
                                            variant="contained"
                                            color="cancel"
                                            onClick={clearHandler()}
                                        >
                                            Reset
                                        </Button>    
                                    </Grid>
                                    <Grid item sx={{ ml: 3, mb: 3, }} >
                                            <Button
                                                variant="contained"
                                                type="submit"
                                                disabled={onLoad}
                                            >
                                                View
                                            </Button>
                                    </Grid>

                                    <Grid item sx={{ ml: 3, mb: 3, }} >
                                        <Grid container spacing={3}>
                                            <Grid item sx={{ ml: 3, mr:3 }} >
                                                <Button
                                                    variant="contained"
                                                    onClick={generateFileHandler("csv")}
                                                    disabled={onLoad}
                                                >
                                                    Generate CSV
                                                </Button>
                                            </Grid>
                                            
                                            <Grid item sx={{ ml: 3, }} >
                                                <Button
                                                    variant="contained"
                                                    onClick={generateFileHandler("pdf")}
                                                    disabled={onLoad}
                                                >
                                                    Generate PDF
                                                </Button>
                                            </Grid>
                                        </Grid>
                                    </Grid>
                                    
                                    {/* <Grid item sx={{ ml: 3, mr: 3, mb: 3, }} >
                                        {onDownload?
                                            <LoadingComponent disableText={true} alignItems="flex-start"/>
                                        :
                                            <Button
                                                variant="contained"
                                                onClick={generatePDFHandler}
                                            >
                                                Generate PDF
                                            </Button>
                                        }
                                    </Grid> */}
                                </ThemeProvider>
                            </Grid>
                        </Grid>
                    </Grid>
                </Grid>
            </form>
        </MainCard>
    );
};

export default SearchPublicNoticeForm;
