// material-ui
import {
    Grid,
    Typography,
    Stack,
    Button,
} from '@mui/material';
import * as React from "react";
import * as HttpUtils from "utils/HttpUtils";
import * as UrlUtils from "utils/ApiPathConst";
import { useNavigate } from "react-router-dom";

import { useLocation } from 'react-router-dom';
// import {paymentPath} from "auth/utils";
// import {poll} from "utils/Utils";
import VisaIcon from "assets/images/icons/visacard.svg";
import MasterIcon from "assets/images/icons/mastercard.svg";
import JcbIcon from "assets/images/icons/jcb.svg";
import UnionPayIcon from "assets/images/icons/unionpay.svg";
import PpsIcon from "assets/images/icons/ppshk.svg";

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

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


const Index = () => {

    const navigate = useNavigate()
    const location = useLocation();

    const [paymentData, setPaymentData] = React.useState({});
    const [onReady, setOnReady] = React.useState(false);
    // const [paymentstatuscode, setPaymentstatuscode] = React.useState("");
    // const [fpsqrcodeurl, setFpsqrcodeurl] = React.useState("");
    // const pasgPath = 'https://fps.payapps.hkicl.com.hk'; //PRD
    // const pasgPath = 'https://sim.fps.payapps.hkicl.com.hk'; //Testing
    // const loadPaymentUrl = "/api/payment/web/";
    // const paymentStatusApi = "/api/payment/status/";
    // const payloadUrl = "/api/payment/wallet/fps/enquiryfpspayload/";
    // const receiverUrl = "/noti-api/payment/payment-notification";

    React.useEffect(() => {
        if (location.state != undefined) {
            setPaymentData(location.state)
        }
    }, []);

    React.useEffect(() => {
        if (Object.keys(paymentData).length > 0){
            setOnReady(true);
            loadForm();
        }
    }, [paymentData]);

    const loadForm = () => {
        // const timeoutdatetime = "2023-10-26T09:04:30Z[UTC]"
        // const convertedDateString = timeoutdatetime.replace("[UTC]", "");
        // setFpsmerchanttimeoutdatetime(convertedDateString)

        localStorage.removeItem("transactionid")
        localStorage.removeItem("webtoken")
        localStorage.setItem("transactionid", paymentData.transactionid)
        localStorage.setItem("webtoken", paymentData.webtoken)

        HttpUtils.post({
            url: UrlUtils.LOAD_PAYMENT_URL+(paymentData.type=="PPS"?"pps":"creditcard"),
            params:{
                "transactionid": paymentData.transactionid,
                //"apprefid:": paymentData.transactionid,
                "webtoken": paymentData.webtoken,
                "paymentmethod":paymentData.paymentMethod,
                "order": { 
                    "totalamount":paymentData.amount,
                    "currency":"HKD",
                    "orderdetail": 
                    [ 
                        { 
                            "itemid": "1",
                            "qty":"1",
                            "unitprice":paymentData.amount,
                            "amount":paymentData.amount
                        },
                    ]
                },
                // "locale":"<locale>",
                // "eserviceid":"<eserviceid>",
                 "returnurl": "https://"+window.location.hostname+"/paymentPage/callback"
            },
            ///{state:{transactionid:paymentData.transactionid,webtoken:paymentData.webtoken} }
            onSuccess: function(responseData){
                /*
                    {
                        "transactionid": "<transactionid>",
                         "redirecturl": "<redirecturl>"
                    }
                */
               //window.open(responseData.redirecturl);
               window.location.assign(responseData.redirecturl);
            }
        });
    }

    const cancelPayment = () => {
        navigate("/dashboard");
    }

    const getIcon = () => {
        if(paymentData.type=="Visa") return VisaIcon;
        if(paymentData.type=="Mastercard") return MasterIcon;
        if(paymentData.type=="UnionPay") return UnionPayIcon;
        if(paymentData.type=="JCB") return JcbIcon;
        if(paymentData.type=="PPS") return PpsIcon;
    }

    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={{ pt: 2 }}>公共啟事： 信用卡付款</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={12} >

                                    <Typography variant="h3" sx={{ ml: 8, mt: 4, mr: 8, textAlign: "center" }}>
                                        <img src={getIcon()} width="80" height="80" alt={paymentData.type}></img>
                                        <br />
                                            <FormattedMessage id="payFee"/>
                                        <br />
                                        {"$HK " + paymentData.amount}
                                    </Typography>


                                    <Typography variant="h3" sx={{ ml: 8, mt: 4, mr: 8, textAlign: "center" }}>
                                        <Button
                                            component="span"
                                            variant="contained"
                                            size="large"
                                            color="error"
                                            onClick={() => {
                                                cancelPayment();
                                            }}
                                            sx={{ m: 4 }}
                                        >
                                            <FormattedMessage id="payCancel"/>
                                        </Button>
                                    </Typography>
                                </Grid>
                            </center>
                        </Grid>
                    </Grid>
                    {/*row 2*/}
                </Grid >
            )
    );
}

export default Index;