// material-ui
import {
    Grid,
    Typography,
    Stack,
    Button,
    Dialog, DialogTitle, DialogContent, DialogActions
} from '@mui/material';
import * as UrlUtils from "utils/ApiPathConst";
import { useState } from "react";
import * as HttpUtils from "utils/HttpUtils";
import { useNavigate } from "react-router-dom";
import * as DateUtils from "utils/DateUtils"
import * as FormatUtils from "utils/FormatUtils";


import titleBackgroundImg from 'assets/images/dashboard/gazette-bar.png'
const BackgroundHead = {
    backgroundImage: `url(${titleBackgroundImg})`,
    width: '100%',
    height: '100%',
    backgroundSize: 'contain',
    backgroundRepeat: 'no-repeat',
    backgroundColor: '#0C489E',
    backgroundPosition: 'right'
}

import { PNSPS_BUTTON_THEME, PNSPS_LONG_BUTTON_THEME } from "../../../themes/buttonConst";
import { ThemeProvider } from "@emotion/react";
import { FormattedMessage, useIntl } from "react-intl";
// ==============================|| DASHBOARD - DEFAULT ||============================== //

const Index = ({ record }) => {
    const navigate = useNavigate()

    const [isPopUp, setIsPopUp] = useState(false);
    const [paymentHoldedErrText, setPaymentHoldedErrText] = useState("");
    const [paymentHoldedErr, setPaymentHoldedErr] = useState(false);

    const intl = useIntl();

    function doPayment() {
        setIsPopUp(false);
        let appIdList = [record?.appId]
        handlePaymentCheck(appIdList)
    }

    const handlePaymentCheck = (appIdList) => {
        HttpUtils.post({
            url: UrlUtils.PAYMENT_CHECK,
            params: {
                appIds: appIdList
            },
            onSuccess: (responseData) => {
                const latestData = {};

                responseData.forEach(item => {
                    const { appId, timeDiff } = item;
                    if (latestData[appId] === undefined || timeDiff < latestData[appId].timeDiff) {
                        latestData[appId] = item;
                    }
                });
                const latestDataObjects = Object.values(latestData);
                
                // const filteredData = latestDataObjects.filter(item => item.timeDiff > 20 || item.status !== "APPR");
                const filteredData = latestDataObjects.filter(item => item.timeDiff > 30 || item.status == "CANC" || item.status == "REJT");

                const filteredAppIds = filteredData.map(item => item.appId);

                const appIdsNotInData = appIdList.filter(appId => !latestDataObjects.some(item => item.appId === appId));
                const combinedAppIdsArray = [...appIdsNotInData, ...filteredAppIds];

                const readyToPayment = appIdList.every(appId => combinedAppIdsArray.includes(appId));
                if (readyToPayment) {
                    navigate('/paymentPage', { state: { amount: record.fee, appIdList: appIdList } });
                } else {
                    const appIdsInData = appIdList.filter(appId => !combinedAppIdsArray.some(item => item === appId));
                    const HoldingApplication = latestDataObjects.filter(item => appIdsInData.includes(item.appId));
                    const resultString = HoldingApplication.map(item => item.appNo).join(' , ');
                    setPaymentHoldedErrText(resultString);
                    // setPaymentHoldedErrText(intl.formatMessage({ id: 'MSG.paymentHolded' }, { appNo: record.appNo }));
                    setPaymentHoldedErr(true);
                }
            }
        });
    };

    return (
        (
            <Grid container sx={{ minHeight: '110vh', backgroundColor: '#fff' }} direction="column" justifyContent="flex-start" alignItems="center" >
                <Grid item xs={12} width="100%">
                    <div style={BackgroundHead} width="100%" >
                        <Stack direction="row" height='70px'>
                            <Typography ml={15} color='#FFF' variant="h4" sx={{ display: { xs: 'none', sm: 'none', md: 'block' }, pt: 2 }}>
                                <FormattedMessage id="proofRecord" />
                            </Typography>
                        </Stack>
                    </div>
                </Grid>
                {/*row 1*/}
                <Grid item xs={12} md={12} >
                    <Grid container justifyContent="flex-start" alignItems="center" >
                        <center>
                            <Grid item xs={12} md={8} >
                                <Typography variant="h3" sx={{ textAlign: "left", ml: 4, mr: 4, mt: 4, borderBottom: "1px solid black" }}>
                                    <FormattedMessage id="publicNoticePaymentProofDoneAndPaid" />
                                </Typography>

                                <Typography variant="h4" sx={{ ml: 8, mt: 4, mr: 8, textAlign: "left" }}>
                                    <div dangerouslySetInnerHTML={{ __html: intl.formatMessage({ id: 'MSG.payMsg1' }, { appNo: record.appNo }) }} />
                                    <br />
                                    <FormattedMessage id="MSG.payMsg2_1" />
                                    <span style={{ color: "red" }}>
                                        {DateUtils.datetimeStr(record?.proofPaymentDeadline)}
                                    </span>
                                    <FormattedMessage id="MSG.payMsg2_2" />
                                    <br />
                                    <br />
                                    <div dangerouslySetInnerHTML={{
                                        __html: intl.formatMessage({ id: 'MSG.payMsg3' },
                                            {
                                                issueYear: record?.issueYear,
                                                issueVolume: record?.issueVolume,
                                                issueNo: record?.issueNo,
                                            })
                                    }} />
                                </Typography>

                                <Typography variant="h4" sx={{ ml: 8, mt: 4, mr: 8, textAlign: "left" }}>
                                    <FormattedMessage id="pleaseClickToPay" />：
                                </Typography>

                                <Typography variant="h4" sx={{ ml: 8, textAlign: "left" }}>
                                    <ThemeProvider theme={PNSPS_LONG_BUTTON_THEME}>
                                        <Button
                                            component="span"
                                            variant="contained"
                                            sx={{ ml: { md: 4, lg: 4 }, mr: 4 }}
                                            onClick={() => { setIsPopUp(true) }}
                                        >
                                            <FormattedMessage id="payInstantly" />
                                        </Button>
                                    </ThemeProvider>

                                    <FormattedMessage id="or" />

                                    <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                                        <Button
                                            component="span"
                                            variant="contained"
                                            sx={{ ml: { sm: 4, md: 4, lg: 4 }, mr: 4, mt: { xs: 2, sm: 2 }, mb: { xs: 2, sm: 2 } }}
                                            onClick={() => {
                                                navigate("/publicNotice");
                                            }}
                                        >
                                            <FormattedMessage id="payLater" />
                                        </Button>
                                    </ThemeProvider>
                                </Typography>
                            </Grid>
                        </center>
                    </Grid>
                </Grid>
                <div>
                    <Dialog
                        open={isPopUp}
                        onClose={() => setIsPopUp(false)}
                        PaperProps={{
                            sx: {
                                minWidth: '40vw',
                                maxWidth: { xs: '90vw', s: '90vw', m: '70vw', lg: '30vw' },
                                maxHeight: { xs: '90vh', s: '70vh', m: '70vh', lg: '50vh' }
                            }
                        }}
                    >
                        <DialogTitle>
                            <Typography variant="h3" >
                                <FormattedMessage id="payConfirm" />
                            </Typography>
                        </DialogTitle>
                        <DialogContent style={{ display: 'flex', }}>
                            <Stack direction="column" justifyContent="space-between">
                                <Typography variant="h4">
                                    <FormattedMessage id="totalAmount" /> ($): {FormatUtils.currencyFormat(record.fee)}
                                </Typography>
                            </Stack>
                        </DialogContent>
                        <DialogActions>
                            <Button onClick={() => setIsPopUp(false)}>
                                <Typography variant="h5">
                                    <FormattedMessage id="close" />
                                </Typography></Button>
                            <Button onClick={() => doPayment()}><Typography variant="h5">
                                <FormattedMessage id="confirm" />
                            </Typography></Button>
                        </DialogActions>
                    </Dialog>
                </div>
                {/*row 2*/}
                <div>
                    <Dialog
                        open={paymentHoldedErr}
                        onClose={() => setPaymentHoldedErr(false)}
                        PaperProps={{
                            sx: {
                                minWidth: '40vw',
                                maxWidth: { xs: '90vw', s: '90vw', m: '70vw', lg: '70vw' },
                                maxHeight: { xs: '90vh', s: '70vh', m: '70vh', lg: '60vh' }
                            }
                        }}
                    >
                        <DialogTitle></DialogTitle>
                        <Typography variant="h4" style={{ paddingLeft: '24px' }}><FormattedMessage id="MSG.actionFail" /></Typography>
                        <DialogContent style={{ display: 'flex', }}>
                            <Stack direction="column" justifyContent="space-between">
                                <div dangerouslySetInnerHTML={{ __html: intl.formatMessage({ id: 'MSG.paymentHolded' }, { appNo: paymentHoldedErrText }) }} />
                            </Stack>
                        </DialogContent>
                        <DialogActions>
                            <Button onClick={() => setPaymentHoldedErr(false)} aria-label={intl.formatMessage({ id: 'close' })}>
                                <Typography variant="h5">
                                    <FormattedMessage id="close" />
                                </Typography></Button>
                        </DialogActions>
                    </Dialog>
                </div>
            </Grid >


        )


    );
};

export default Index;
