// 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 FpsIcon from "assets/images/icons/fps.svg";
import expiredQrcodeEN from "assets/images/icons/expiredQrcodeEN.png";
import expiredQrcodeZH from "assets/images/icons/expiredQrcodeZH.png";
import expiredQrcodeCN from "assets/images/icons/expiredQrcodeCN.png";
import { useLocation } from 'react-router-dom';
// import {paymentPath} from "auth/utils";
import {currencyFormat} from "utils/FormatUtils";
// import {poll} 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'
import {FormattedMessage, useIntl} from "react-intl";
const BackgroundHead = {
    backgroundImage: `url(${titleBackgroundImg})`,
    width: '100%',
    height: '100%',
    backgroundSize: 'contain',
    backgroundRepeat: 'no-repeat',
    backgroundColor: '#0C489E',
    backgroundPosition: 'right'
}


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

const Index = () => {
    const navigate = useNavigate()
    const location = useLocation();
    const intl = useIntl();
    const { locale } = intl;

    const [locationData, setLocationData] = React.useState({});
    const [paymentData, setPaymentData] = React.useState({});
    const [onReady, setOnReady] = React.useState(false);
    const [qrCodeTimeout, setqrCodeTimeout] = React.useState(false);
    const [paymentStatusCode, setPaymentStatusCode] = React.useState("");
    const [expiredQrcode, setExpiredQrcode] = React.useState(expiredQrcodeEN);
    
    const [responeData, setResponeDataData] = React.useState({});
    const [fpsTransctionData, setFpsTransctionData] = React.useState({});
    const [fpsmerchanttimeoutdatetime, setFpsmerchanttimeoutdatetime] = React.useState("");
    const [timeDownCount, setTimeDownCount] = React.useState(0);
    const [paymentId, setPaymentId] = React.useState("");
    const [fpsqrcodeurl, setFpsqrcodeurl] = React.useState("");
    const [fpsqrcodeurlPrd, setFpsqrcodeurlPrd] = React.useState("");
    const [fpsqrcodeurlFps, setFpsqrcodeurlFps] = React.useState("");
    const [browserType, setBrowserType] = React.useState("");
    const [sysEnv, setSysEnv] = React.useState("");
    const mobileBrowser = "Mobile";
    const desktopBrowser = "Desktop";
    
    const pasgPathPrd = 'https://fps.payapps.hkicl.com.hk'; //PRD
    const pasgPath = 'https://sim.fps.payapps.hkicl.com.hk'; //Testing
    // const loadPaymentUrl = "/api/payment/wallet/fps";
    // const cancelPaymentUrl = "/api/payment/cancelpayment";
    // const paymentStatusApi = "/api/payment/status/";
    // const payloadUrl = "/api/payment/wallet/fps/enquiryfpspayload/";
    // const receiverUrl = "/noti-api/payment/payment-notification";
    
    //timer
    const currentTimer = React.useRef();
    const [time, setTime] = React.useState(0);

    React.useEffect(() => {
        // console.log (location.state)
        if(Object.keys(location.state).length > 0){
            // console.log (location.state)
            setLocationData(location.state)
            setBrowserType(desktopBrowser)

            if (/Android|webOS|iPhone|iPad|iPod|Opera Mini/i.test(navigator.userAgent)) {
                // console.log('Mobile web browser');
                setBrowserType(mobileBrowser)
                // setFpsqrcodeurl(openPASGUrl)
            } else {
                // console.log('Desktop web browser');
                setBrowserType(desktopBrowser)
            }
        }
    }, []);

    React.useEffect(() => {
        // console.log (locationData)
        if (Object.keys(locationData).length > 0){
            setPaymentData(locationData)
            // loadForm();
        }
    }, [locationData]);

    React.useEffect(() => {
        // console.log (locationData)
        if (locale === 'zh-HK'){
            setExpiredQrcode(expiredQrcodeZH)
        } else if (locale === 'en'){
            setExpiredQrcode(expiredQrcodeEN)
        } else {
            setExpiredQrcode(expiredQrcodeCN)
        }
    }, [locale]);

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

    React.useEffect(() => {
        // console.log(responeData)
        if(Object.keys(responeData).length > 0 && fpsmerchanttimeoutdatetime!=""){
            setFpsTransctionData(responeData)
        }
    }, [responeData]);

    React.useEffect(() => {
        // console.log(fpsTransctionData)
        if(Object.keys(fpsTransctionData).length > 0 ){
            setPaymentId(fpsTransctionData.paymentid)
            currentTimer.current = setInterval(() => {
                setTime((prevTime) => prevTime + 1);
            }, 1000);
            setOnReady(true);
            return () => clearInterval(currentTimer.current);
        }
    }, [fpsTransctionData]);


    const loadForm = () => {
        const webtoken = paymentData.webtoken;
        const transactionid = paymentData.transactionid;
        console.log(webtoken)
        console.log(transactionid)
        localStorage.removeItem("transactionid")
        localStorage.removeItem("webtoken")
        localStorage.setItem("transactionid", transactionid)
        localStorage.setItem("webtoken", webtoken)

        HttpUtils.post({
            url: UrlUtils.LOAD_PAYMENT_FPS_URL,
            params:{
                "transactionid": transactionid,
                "webtoken": webtoken,
                "paymentmethod":"04,BCFP,FPS",
                "order": { 
                    "totalamount":paymentData.amount,
                    "currency":"HKD",
                    "orderdetail": 
                    [ 
                        { 
                            "itemid": "1",
                            "qty":"1",
                            "unitprice":paymentData.amount,
                            "amount":paymentData.amount
                        },
                    ]
                },
                // "locale":"<locale>",
                // "eserviceid":"<eserviceid>"
            },
            onSuccess: function(responseData){
                /*
                    {
                        "paymentid": "<paymentid>",
                        "paymentstatus": "<paymentstatus>",
                        "fpsmerchanttimeoutdatetime": <fpsmerchanttimeoutdatetime>,
                        "fpsqrcodeimgbase64": "<fpsqrcodeimgbase64>",
                        "fpsqrcodeurl": "<fpsqrcodeurl>"
                    }
                */
               setResponeDataData(responseData)
               const timeoutdatetime = responseData.fpsmerchanttimeoutdatetime
               setSysEnv(responseData.sysEnv)
               const searchString = "[UTC]";
               let convertedDateString = "";
               if ( timeoutdatetime.toString().includes(searchString) ){
                    convertedDateString = timeoutdatetime.replace("[UTC]", "");
                } else {
                    convertedDateString = timeoutdatetime;
                }
                setFpsmerchanttimeoutdatetime(convertedDateString)
               
                const parsedUrl = new URL(responseData.fpsqrcodeurl);
                const fpsqrcodeurl = "https://"+window.location.hostname+'/payment'+parsedUrl.pathname;
                const fpsqrcodeurlwithFps = "https://"+"fps."+window.location.hostname+parsedUrl.pathname;
                console.log(parsedUrl)
                console.log(fpsqrcodeurl)
                console.log(fpsqrcodeurlwithFps)
 
                const openPASGUrl = pasgPath + '?pay_req_obj=' + encodeURIComponent(fpsqrcodeurlwithFps) + '&callback='
                                 + encodeURIComponent("https://"+window.location.hostname+ '/paymentPage/fps/fpscallback?&PAYMENT_ID='+localStorage.getItem("paymentId"));
                const openPASGUrlPrd = pasgPathPrd + '?pay_req_obj=' + encodeURIComponent(fpsqrcodeurlwithFps) + '&callback='
                                 + encodeURIComponent("https://"+window.location.hostname+ '/paymentPage/fps/fpscallback?&PAYMENT_ID='+localStorage.getItem("paymentId"));
                const openPASGUrlPrdFps = pasgPath + '?pay_req_obj=' + encodeURIComponent(fpsqrcodeurlwithFps) + '&callback='
                                 + encodeURIComponent("https://"+window.location.hostname+ '/paymentPage/fps/fpscallback?&PAYMENT_ID='+localStorage.getItem("paymentId"));
                // const openPASGUrl = pasgPath + '?pay_req_obj=' + encodeURIComponent(fpsqrcodeurlwithFps) + '&callback='
                //                  + encodeURIComponent("https://"+window.location.hostname+ '/paymentPage/fps/fpscallback?TRANSACTION_ID='+transactionid+"&WEB_TOKEN="+webtoken+"&PAYMENT_ID="+localStorage.getItem("paymentId"));
                // const openPASGUrlPrd = pasgPathPrd + '?pay_req_obj=' + encodeURIComponent(fpsqrcodeurlwithFps) + '&callback='
                //                  + encodeURIComponent("https://"+window.location.hostname+ '/paymentPage/fps/fpscallback?TRANSACTION_ID='+transactionid+"&WEB_TOKEN="+webtoken+"&PAYMENT_ID="+localStorage.getItem("paymentId"));
                // const openPASGUrlPrdFps = pasgPath + '?pay_req_obj=' + encodeURIComponent(fpsqrcodeurlwithFps) + '&callback='
                //                  + encodeURIComponent("https://"+window.location.hostname+ '/paymentPage/fps/fpscallback?TRANSACTION_ID='+transactionid+"&WEB_TOKEN="+webtoken+"&PAYMENT_ID="+localStorage.getItem("paymentId"));
                setFpsqrcodeurl(openPASGUrl)
                setFpsqrcodeurlPrd(openPASGUrlPrd)
                setFpsqrcodeurlFps(openPASGUrlPrdFps)
            }
        });

        //testing
        // const timeoutdatetime = "2024-11-18T07:04:35Z[UTC]"
        // const convertedDateString = timeoutdatetime.replace("[UTC]", "");
        // setFpsmerchanttimeoutdatetime(convertedDateString)
        // setPaymentId("C202310268000681")
        // const responseData= 
        // {
        //     "paymentid": "C202310268000681",
        //     "paymentstatus": "INPR",
        //     "fpsmerchanttimeoutdatetime": "2024-11-18T07:04:35Z[UTC]",
        //     "fpsqrcodeimgbase64": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAAEsCAYAAAB5fY51AAAuyklEQVR4Xu3dfcy/d1nff2IAAAAASUVORK5CYII=",
        //     "fpsqrcodeurl": "http://127.0.0.1:8080/api/payment/wallet/fps/enquiryfpspayload/vm.JKDDlTOavR3ASviSwUnS1Lw4-"
        // }
        // setResponeDataData(responseData)
        // const parsedUrl = new URL(responseData.fpsqrcodeurl);
        // const fpsqrcodeurl = "https://"+window.location.hostname+'/payment'+parsedUrl.pathname;
        // const fpsqrcodeurlwithFps = "https://"+"fps."+window.location.hostname+parsedUrl.pathname;
        // console.log(parsedUrl)
        // console.log(fpsqrcodeurl)
        // console.log(fpsqrcodeurlwithFps)

        // const openPASGUrl = pasgPath + '?pay_req_obj=' + encodeURIComponent(fpsqrcodeurl) + '&callback='
        //                     + encodeURIComponent("https://"+window.location.hostname+ '/paymentPage/fps/fpscallback?TRANSACTION_ID='+transactionid+"&WEB_TOKEN="+webtoken+"&PAYMENT_ID="+localStorage.getItem("paymentId"));
        // const openPASGUrlPrd = pasgPathPrd + '?pay_req_obj=' + encodeURIComponent(fpsqrcodeurl) + '&callback='
        //                     + encodeURIComponent("https://"+window.location.hostname+ '/paymentPage/fps/fpscallback?TRANSACTION_ID='+transactionid+"&WEB_TOKEN="+webtoken+"&PAYMENT_ID="+localStorage.getItem("paymentId"));
        // const openPASGUrlPrdFps = pasgPath + '?pay_req_obj=' + encodeURIComponent(fpsqrcodeurlwithFps) + '&callback='
        //                     + encodeURIComponent("https://"+window.location.hostname+ '/paymentPage/fps/fpscallback?TRANSACTION_ID='+transactionid+"&WEB_TOKEN="+webtoken+"&PAYMENT_ID="+localStorage.getItem("paymentId"));
        // setFpsqrcodeurl(openPASGUrl)
        // setFpsqrcodeurlPrd(openPASGUrlPrd)
        // setFpsqrcodeurlFps(openPASGUrlPrdFps)

    }

    const getPaymentStatus = () => {
        if(Object.keys(paymentData).length > 0){
            HttpUtils.post({
                url: UrlUtils.PAYMENT_STATUS_API,
                params:{
                    "apprefid": paymentData.transactionid,
                    // "webtoken": paymentData.webtoken, 
                    "transactionid":Number(paymentData.transactionid)  
                },
                onSuccess: function(responseData){
                    const paymentstatuscode = responseData.paymentdetail.result.paymentstatuscode;
                    setPaymentStatusCode(paymentstatuscode)
                    if (paymentstatuscode != "" && paymentstatuscode != "INPR" ){
                        if (paymentstatuscode === 'APPR') {
                            // const timestamp = Date.now();
                            let page = '/paymentPage/fps/ackpage';
                            let stateParams = { state: { transactionid: paymentData.transactionid} }
                            navigate(page, stateParams);
                        } else if (paymentstatuscode === 'CANC') {
                            // const timestamp = Date.now();
                            let page = '/paymentPage/fps/ackpage';
                            let stateParams = { state: { transactionid: paymentData.transactionid} }
                            navigate(page, stateParams);
                        } else {
                            // window.top.location.href = paymentPath + payment.config.errPagePath;
                            alert("ERROR")
                        }
                    }
                },
                onError: function(){
                    alert("ERROR")
                    // cancelPayment()
                    // clearInterval(currentTimer.current);
                }
            });
        }
    };
    
    React.useEffect(() => {
        const timeOutDate = new Date(fpsmerchanttimeoutdatetime);
        const currentTime = new Date;
        const timedowncount = Math.round((timeOutDate.getTime() - currentTime.getTime()) / 1000);
        // console.log(time)
        // console.log(timeOutDate)
        // console.log(currentTime)
        // console.log(timeOutDate.getTime()-currentTime.getTime())
        if (browserType === desktopBrowser){
            getPaymentStatus();
            if (timeOutDate.getTime()<currentTime.getTime()){
                // console.log("stop");
                clearInterval(currentTimer.current);
                setqrCodeTimeout(true)
                setTimeDownCount(0);
                // cancelPayment()
            }else{
                setTimeDownCount(timedowncount);
            }
        }
    },[time])

    const cancelPayment = ()=>{
        if (Object.keys(paymentData).length>0){
            getPaymentStatus()
            if (paymentStatusCode === "INPR"){
                HttpUtils.post({
                    url: UrlUtils.CANCEL_PAYMENT_URL,
                    params:{
                        "transactionid": paymentData.transactionid,
                        "webtoken": paymentData.webtoken,
                        "paymentid": fpsTransctionData.paymentid
                    },
                    onSuccess: function(){
                        navigate('/paymentPage/fps/ackpage');
                        let page = '/paymentPage/fps/ackpage';
                        let stateParams = { state: { transactionid: paymentData.transactionid} }
                        navigate(page, stateParams);                    
                    }
                });
            }
        }
    }

    const mobliePayment = ()=>{
        window.location.assign(fpsqrcodeurl);
    }

    const mobliePaymentPrd = ()=>{
        window.location.assign(fpsqrcodeurlPrd);
    }

    const mobliePaymentFps = ()=>{
        window.location.assign(fpsqrcodeurlFps);
    }

    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 }}>
                                    <FormattedMessage id="publicNoticePaymentFPSPay"/>
                                </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" }}>
                                        <FormattedMessage id="payAlert"/>
                                        <br /><br />
                                        <img src={FpsIcon} width="80" height="80" alt="FPS"></img>
                                        <br />
                                        <FormattedMessage id="payTotalDeatail"/>
                                        <br />
                                        {"HK$ " + currencyFormat(paymentData.amount)}
                                    </Typography>
                                    {browserType==mobileBrowser?
                                        <Typography variant="h3" sx={{ ml: 8, mt: 4, mr: 8, textAlign: "center" }}>
                                            {
                                                sysEnv=="prod"?
                                                    <Button
                                                        component="span"
                                                        variant="contained"
                                                        size="large"
                                                        color="primary"
                                                        onClick={()=>{
                                                            mobliePaymentPrd();
                                                        }}
                                                        sx={{ m: 4 }}
                                                    >請選擇支付程式付款</Button>
                                                :
                                                <>
                                                    <Button
                                                        component="span"
                                                        variant="contained"
                                                        size="large"
                                                        color="primary"
                                                        onClick={()=>{
                                                            mobliePayment();
                                                        }}
                                                        sx={{ m: 4 }}
                                                    >請選擇支付程式付款-Testing</Button>
                                                    <Button
                                                        component="span"
                                                        variant="contained"
                                                        size="large"
                                                        color="primary"
                                                        onClick={()=>{
                                                            mobliePaymentFps();
                                                        }}
                                                        sx={{ m: 4 }}
                                                    >請選擇支付程式付款-fps prefix</Button>
                                                </>
                                            }
                                        </Typography>
                                        :
                                        <Typography variant="h3" sx={{ ml: 8, mt: 4, mr: 8, textAlign: "center" }}>
                                            <FormattedMessage id="fpsQrcodeTitle1"/>
                                            <br />
                                            { 
                                                !qrCodeTimeout?
                                                <img src={fpsTransctionData.fpsqrcodeimgbase64} alt="QR Code"/>
                                                :<img src={expiredQrcode} alt="Expired QR Code"/>
                                            }
                                            <br />
                                            {"["+paymentId+"]"}
                                            <br/>
                                            
                                            {
                                                timeDownCount<=0?
                                                <FormattedMessage id="fpsQrcodeExpired"/>:
                                                <>
                                                    <FormattedMessage id="fpsQrcodeTitle2"/>
                                                    <br />
                                                    <FormattedMessage id="fpsQrcodeTitle3"/>
                                                    <br />
                                                    <FormattedMessage id="fpsQrcodeTitle4"/>&nbsp;
                                                    {timeDownCount}&nbsp; 
                                                    <FormattedMessage id="fpsQrcodeTitle5"/>
                                                </>
                                            }
                                        </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;
