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

import Loadable from 'components/Loadable';
const LoadingComponent = Loadable(React.lazy(() => import('pages/extra-pages/LoadingComponent')));

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 {
    // useEffect,
    useState
} from "react";
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 = () => {
    const params = useParams();
    const navigate = useNavigate()
    const [fee, setFee] = useState(0);

    const [record, setRecord] = React.useState({});
    const [onReady, setOnReady] = React.useState(false);
    const [isPopUp, setIsPopUp] = useState(false);
    const [paymentHoldedErrText, setPaymentHoldedErrText] = React.useState("");
    const [paymentHoldedErr, setPaymentHoldedErr] = React.useState(false);

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

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

    React.useEffect(() => {
        setOnReady(true);
    }, [record]);

    const isAfter = checkIsOnlyOnlinePayment();


    const loadForm = () => {
        if (params.id > 0) {
            HttpUtils.get({
                url: UrlUtils.GET_PROOF_PAY + "/" + params.id,
                onSuccess: (responseData) => {
                    // if (!responseData.data?.id) {
                    //     navigate("/proof/search");
                    // }
                    setRecord(responseData.data);
                    setFee(responseData.data.fee);
                },
                onError: () => {

                }
            });
        }
    }

    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 > 30 || item.status !== "APPR");
                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: 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 (
        !onReady ?
            <Grid container sx={{ minHeight: '87vh', mb: 3 }} direction="column" justifyContent="center" alignItems="center">
                <Grid item>
                    <LoadingComponent />
                </Grid>
            </Grid>
            :
            (
                <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} >
                                    {isAfter ? (
                                    <Typography
                                        variant="h4"
                                        sx={{ textAlign: "left", ml: 8, mr: 4, mt: 4,
                                            textDecoration: "underline",
                                            textDecorationThickness: "2px",
                                            textUnderlineOffset: "4px" }}
                                    >
                                        <FormattedMessage id="proofPaymentHeader_online2" />
                                    </Typography>
                                    ) : (
                                    <Typography
                                        variant="h4"
                                        sx={{
                                        textAlign: "left",
                                        ml: 4,
                                        mr: 4,
                                        mt: 4,
                                        textDecoration: "underline",
                                        textDecorationThickness: "2px",
                                        textUnderlineOffset: "4px"
                                        }}
                                    >
                                        <FormattedMessage id="proofPaymentHeader_online" />
                                    </Typography>
                                    )}

                                    <Typography variant="h5" sx={{ ml: 8, mt: 4, mr: 8, textAlign: "left" }}>
                                        <div dangerouslySetInnerHTML={{
                                            __html: intl.formatMessage(
                                                {
                                                    id: 'proofPaymentBody_online'
                                                },
                                                {
                                                    appNo: record?.appNo,
                                                }
                                            )
                                        }} />
                                        <br />
                                        <div dangerouslySetInnerHTML={{
                                            __html: intl.formatMessage(
                                                {
                                                    id: 'proofPaymentBody_online2'
                                                },
                                                {
                                                    paymentDeadline: DateUtils.formatDateForLocale(record?.expiryDate, intl, locale),
                                                }
                                            )
                                        }} />
                                        <br />
                                        {checkPaymentSuspension()?
                                            <div>
                                                <Typography style={{ textAlign: "flex-start", color: "red"  }}>
                                                    <div dangerouslySetInnerHTML={{ __html: intl.formatMessage({ id: "suspensionMessageText" }) }} />
                                                </Typography>
                                                <br />
                                            </div>:null
                                        }
                                    </Typography>

                                    {!checkPaymentSuspension()?
                                        <Typography variant="h4" sx={{ ml: 8, textAlign: "left" }}>
                                            <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 } }}
                                                    sx={{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>:null
                                    }

                                    <Typography variant="h4" sx={{ ml: 8, mt: 4, mr: 8, textAlign: "left" }}>
                                        <div dangerouslySetInnerHTML={{
                                            __html: intl.formatMessage(
                                                {
                                                    id: 'proofPaymentBody_online3'
                                                }
                                            )
                                        }} />
                                        <br />
                                    </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(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;
