// material-ui
import {
    Button,
    Grid, TextField,
    Autocomplete,
    Typography,
    Dialog, DialogTitle, DialogContent, DialogActions,
} from '@mui/material';
import MainCard from "components/MainCard";
import * as React from "react";
import * as FormatUtils from "utils/FormatUtils";
import * as DateUtils from "utils/DateUtils";
import * as UrlUtils from "utils/ApiPathConst";
import * as HttpUtils from "utils/HttpUtils";
// import { useNavigate } from "react-router-dom";
// import { notifyDownloadSuccess } from 'utils/CommonFunction';
import { PNSPS_BUTTON_THEME } from "../../../themes/buttonConst";
import { ThemeProvider } from "@emotion/react";
import { useIntl } from "react-intl";


// ==============================|| DASHBOARD - DEFAULT ||============================== //


const SearchPublicNoticeForm = ({ applySearch, issueComboData }) => {

    const [isFailPopUp, setIsFailPopUp] = React.useState(false);
    const [failText, setFailText] = React.useState("");

    const [confirmPopUp, setConfirmPopUp] = React.useState(false);
    const [dueDate, setDueDate] = React.useState(DateUtils.dateValue(DateUtils.dateValue((new Date().setDate(new Date().getDate() + 1)))));

    // const [isSuccessPopUp, setIsSuccessPopUp] = React.useState(false);
    // const [resultCount, setResultCount] = React.useState(0);
    // const [dnIdList, setDnIdList] = React.useState([]);

    const [issueSelected, setIssueSelected] = React.useState({});
    // const [paymentCount, setPaymentCount] = React.useState(0);
    // const [publishCount, setPublishCount] = React.useState(0);
    const [issueCombo, setIssueCombo] = React.useState([]);
    const [waitDownload, setWaitDownload] = React.useState(false);
    // const navigate = useNavigate()

    const intl = useIntl();
    const { locale } = intl;

    React.useEffect(() => {
        if (issueComboData && issueComboData.length > 0) {
            setIssueCombo(issueComboData);
        }
    }, [issueComboData]);

    // React.useEffect(() => {
    //     setPaymentCount(_paymentCount);
    // }, [_paymentCount]);

    // React.useEffect(() => {
    //     setPublishCount(_publishCount);
    // }, [_publishCount]);

    React.useEffect(() => {
        onPreView();
    }, [issueSelected]);

    function getIssueLabel(data) {
        let issueYear = data.issueYear
        let volume = data.volume;
        let issueNo = data.issueNo;
        let issueDate = data.issueDate;
        if (locale === 'zh-HK') {
            return issueYear
                + " 第" + volume + "卷,"
                + " 第" + issueNo + "期,"
                + " " + DateUtils.dateFormat(issueDate, "YYYY年MM月DD日")
                + " (" + DateUtils.getWeekdayStr_ZH(issueDate) + ")";
        } else if (locale === 'zh-CN') {
            return issueYear
                + " 第" + volume + "卷,"
                + " 第" + issueNo + "期,"
                + " " + DateUtils.dateFormat(issueDate, "YYYY年MM月DD日")
                + " (" + DateUtils.getWeekdayStr_CN(issueDate) + ")";
        }
        return issueYear
            + " Vol. " + FormatUtils.zeroPad(volume, 3)
            + ", No. " + FormatUtils.zeroPad(issueNo, 2)
            + ", " + DateUtils.dateFormat(issueDate, "D MMM YYYY (ddd)");
    }

    const onSubmit = () => {
        if (!issueSelected?.id) {
            setFailText("Fail Create: Please select Gazette Issue.");
            setIsFailPopUp(true);
            return;
        } else {
            setDueDate(DateUtils.dateValue((new Date().setDate(new Date().getDate() + 1))));
            doDnExport();
        }
    };

    const doDnExport= () => {
        // setConfirmPopUp(false);
        setWaitDownload(true)
        HttpUtils.fileDownload({
            url: UrlUtils.GDN_EXPORT,
            params: {
                issueId: issueSelected.id
            },
            onResponse: () => {
                setTimeout(()=> setWaitDownload(false), 500)
                // location.reload();
            }
        });
    }

    // const fileDownload = () => {
    //     HttpUtils.fileDownload({
    //         method: 'post',
    //         url: UrlUtils.DEMAND_NOTE_EXPORT,
    //         params: {
    //             "dnIdList": dnIdList
    //         },
    //         onSuccess: function () {
    //             notifyDownloadSuccess();
    //         }
    //     });
    // }

    // const onNavigate = () => {
    //     setIsSuccessPopUp(false);
    //     if (resultCount > 0)
    //         navigate('/paymentPage/demandNote');
    // };

    const onPreView = () => {
        if (!issueSelected?.id) {
            return;
        }
        const temp = {
            issueId: issueSelected.id,
            start:0,
            limit:10
        };
        applySearch(temp);
    };

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

            <form>
                {/*row 1*/}
                <Grid container sx={{ backgroundColor: '#ffffff', pt:4, pl:4, pb:4 }} width="98%" spacing={3} >
                    {/*row 1*/}
                    <Grid item justifyContent="space-between" alignItems="center" >
                        <Typography variant="h5" >
                            Please Select Gazette Issue :
                        </Typography>
                    </Grid>
                    {/*row 2*/}

                    <Grid item xs={9} s={6} md={5} lg={3}>
                        <Autocomplete
                            disablePortal
                            size="small"
                            id="issueId"
                            options={issueCombo}
                            value={issueSelected}
                            inputValue={(issueSelected?.id) ? getIssueLabel(issueSelected) : ""}
                            getOptionLabel={(option) => getIssueLabel(option)}
                            onChange={(event, newValue) => {
                                if (newValue !== null) {
                                    setIssueSelected(newValue);
                                }
                            }}
                            sx={{
                                '& .MuiInputBase-root': { alignItems: 'center' },
                                '& .MuiAutocomplete-endAdornment': { top: '50%', transform: 'translateY(-50%)' },
                                '& .MuiOutlinedInput-root': { height: 40 }
                            }}
                            renderInput={(params) => (
                                <TextField {...params}
                                    label="Gazette Issue"
                                    InputLabelProps={{
                                        shrink: true
                                    }}
                                />
                            )}
                            clearText={intl.formatMessage({ id: "muiClear" })}
                            closeText={intl.formatMessage({ id: "muiClose" })}
                            openText={intl.formatMessage({ id: "muiOpen" })}
                            noOptionsText={intl.formatMessage({ id: "muiNoOptions" })}
                        />
                    </Grid>
       
                    <Grid item >
                        <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                            <Button
                                variant="contained"
                                onClick={onSubmit}
                                color="success"
                                disabled={waitDownload}
                                sx={{ minWidth: 150 }}
                            >
                                Export
                            </Button>
                        </ThemeProvider>
                    </Grid>

                    {/* <Grid item >
                        <Grid container display="flex" alignItems={"center"} spacing={3}>
                            <Grid item  >
                                <Typography variant="h5">Pending Payment: {paymentCount}</Typography>
                            </Grid>

                            <Grid item  >
                                <Typography variant="h5">Pending Publish: {publishCount}</Typography>
                            </Grid>
                        </Grid>
                    </Grid> */}
                </Grid>
            </form>
            <div>
                <Dialog
                    open={isFailPopUp}
                    onClose={() => setIsFailPopUp(false)}
                    PaperProps={{
                        sx: {
                            minWidth: '40vw',
                            maxWidth: { xs: '90vw', s: '90vw', m: '70vw', lg: '70vw' },
                            maxHeight: { xs: '90vh', s: '70vh', m: '70vh', lg: '60vh' }
                        }
                    }}
                >
                    <DialogTitle><Typography variant="h3">Action Fail</Typography></DialogTitle>
                    <DialogContent style={{ display: 'flex', }}>
                        <Typography variant="h4" style={{ padding: '16px' }}>{failText}</Typography>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={() => setIsFailPopUp(false)}><Typography variant="h5">OK</Typography></Button>
                    </DialogActions>
                </Dialog>
            </div>
            <div>
                <Dialog
                    open={confirmPopUp}
                    onClose={() => setConfirmPopUp(false)}
                    PaperProps={{
                        sx: {
                            minWidth: '40vw',
                            maxWidth: { xs: '90vw', s: '90vw', m: '70vw', lg: '70vw' },
                            maxHeight: { xs: '90vh', s: '70vh', m: '70vh', lg: '60vh' }
                        }
                    }}
                >
                    <DialogTitle><Typography variant="h3">Create Confirm</Typography></DialogTitle>
                    <DialogContent style={{ display: 'flex', }}>
                        <Grid container alignItems={"center"}>
                            <Grid item md={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
                                <Typography variant="h4" style={{ padding: '16px' }}>Due Date: </Typography>

                            </Grid>
                            <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
                                <TextField
                                    fullWidth
                                    type="date"
                                    defaultValue={dueDate}
                                    InputProps={{ inputProps: { min: DateUtils.dateValue(new Date()) } }}
                                    onChange={(newValue) => {
                                        setDueDate(newValue.currentTarget.value)
                                    }}
                                    InputLabelProps={{
                                        shrink: true
                                    }}
                                />
                            </Grid>
                        </Grid>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={() => setConfirmPopUp(false)}><Typography variant="h5">Cancel</Typography></Button>
                        <Button onClick={() => doDnCreate()}><Typography variant="h5">Confirm</Typography></Button>
                    </DialogActions>
                </Dialog>
            </div>
        </MainCard>
    );
};

export default SearchPublicNoticeForm;
