import * as React from "react";
import * as HttpUtils from "utils/HttpUtils";
import * as UrlUtils from "utils/ApiPathConst";
import Loadable from 'components/Loadable';
const MultiPaymentWindow = Loadable(React.lazy(() => import('./MultiPaymentWindow')));
const DataGrid = Loadable(React.lazy(() => import('./Details_Public/DataGrid')));
// const FPS = Loadable(React.lazy(() => import('./FPS')));
import { useEffect, useState } from "react";
import { useNavigate, useLocation } from "react-router-dom";
// import * as FormatUtils from "utils/FormatUtils";
// const LoadingComponent = Loadable(React.lazy(() => import('pages/extra-pages/LoadingComponent')));
import {getBowserType, local, preferpaymentmethods} from "auth/utils";

import {
    Button,
    Grid,
    Typography,
    Stack,
    Box,
    Dialog, DialogTitle, DialogContent, DialogActions,
} from '@mui/material';

import titleBackgroundImg from 'assets/images/dashboard/gazette-bar.png'
import {ThemeProvider} from "@emotion/react";
import {PNSPS_BUTTON_THEME} from "../../themes/buttonConst";
import {
    FormattedMessage,
    useIntl
} 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 intl = useIntl();
    const { locale } = intl;

    // const local = {en:"en-us", zh:"zh-hk", cn:"zh-cn"};
    // const preferpaymentmethods = ['visa', 'mastercard', 'pps', 'creditcard', 'fps'];
    const [totalAmount, setTotalAmount] = useState(0);
    const [appIds, setAppIds] = useState([]);


    //statusWindow
    const [open, setOpen] = useState(false);
    const [availableMethods, setAvailableMethods] = useState([]);
    const [paymentLimit, setPaymentLimit] = useState([]);
    const [transactionData, setTransactionData] = useState({});
    const [fpsStatus, setFPSStatus] = useState({});
    const [creditCardStatus, setCreditCardStatus] = useState({});
    const [unionPayStatus, setUnionPayStatus] = useState({});
    const [ppsStatus, setPPSStatus] = useState({});
    const [selectedPaymentMethod, setSelectedPaymentMethod] = useState("");
    const [confirmPayment, setConfirmPayment] = useState(false);
    const [afterConfirmPayment, setAfterConfirmPayment] = useState(false);

    const [itemList, setItemList] = useState([]);
    const [onReady, setOnReady] = useState(false);
    const [onPayment, setOnPayment] = useState(false);
    const [isFullScreen, setIsFullScreen] = useState(false);
    
    const [expiryDateErrText, setExpiryDateErrText] = React.useState("");
    const [expiryDateErr, setExpiryDateErr] = React.useState(false);
    
    const [browserType, setBrowserType] = React.useState("");
    const mobileBrowser = "Mobile";
    const desktopBrowser = "Desktop";

    useEffect(() => {
        setAppIds(location.state?.appIdList ?? [])
        setTotalAmount(location.state?.amount ?? 2000)
        localStorage.removeItem("webtoken");
        localStorage.removeItem("transactionid");
        localStorage.removeItem("paymentId");
        if (getBowserType() === "PC_Browser"){
            setIsFullScreen(false)
            setBrowserType(desktopBrowser)
        } else {
            setIsFullScreen(true)
            setBrowserType(mobileBrowser)
        }
    }, []);

    useEffect(() => {
        if (appIds != [] && appIds.length > 0)
            getAppList();
    }, [appIds]);

    // const handleClose = () =>  {
    //     // handleReset()
    //     setOpen(false);
    //     // getTransactionId()
    //     // getAvailablePayment()
    // };

    const paymentClick = () => {
        setTotalAmount(totalAmount);
        setSelectedPaymentMethod("")
        setConfirmPayment(false)
        if (totalAmount > 0) {
            getAvailablePayment()
            getTransactionId()
            setOpen(true)
        }
    };

    useEffect(() => {
        if (afterConfirmPayment) {
            setOnPayment(true)
            // setOpen(false);
            // let transactionid = "";
            // let webtoken = "";

            let page = "";
            let stateParams = {};
            let paymentMethod = "";
            if (selectedPaymentMethod === "FPS") {
                page = '/paymentPage/fps';
                stateParams = { state: { amount: totalAmount, transactionid: transactionData.transactionid, webtoken: transactionData.webtoken } }
                paymentMethod = "04,BCFP,FPS";
            } else if (selectedPaymentMethod === "Visa") {
                page = '/paymentPage/card';
                stateParams = { state: { amount: totalAmount, transactionid: transactionData.transactionid, webtoken: transactionData.webtoken, type: "Visa", paymentMethod: "02,BCMP,CreditCard" } }
                paymentMethod = "02,BCMP,CreditCard";
            } else if (selectedPaymentMethod === "MasterCard") {
                page = '/paymentPage/card';
                stateParams = { state: { amount: totalAmount, transactionid: transactionData.transactionid, webtoken: transactionData.webtoken, type: "MasterCard", paymentMethod: "02,BCMP,CreditCard" } }
                paymentMethod = "02,BCMP,CreditCard";
            } else if (selectedPaymentMethod === "JCB") {
                page = '/paymentPage/card';
                stateParams = { state: { amount: totalAmount, transactionid: transactionData.transactionid, webtoken: transactionData.webtoken, type: "JCB", paymentMethod: "02,BCMP,CreditCard" } }
                paymentMethod = "02,BCMP,CreditCard";
            } else if (selectedPaymentMethod === "UnionPay") {
                page = '/paymentPage/card';
                stateParams = { state: { amount: totalAmount, transactionid: transactionData.transactionid, webtoken: transactionData.webtoken, type: "UnionPay", paymentMethod: "03,BCMP,CreditCard" } }
                paymentMethod = "03,BCMP,CreditCard";
            } else if (selectedPaymentMethod === "PPS") {
                page = '/paymentPage/card';
                stateParams = { state: { amount: totalAmount, transactionid: transactionData.transactionid, webtoken: transactionData.webtoken, type: "PPS", paymentMethod: "01,PPSB,PPS" } }
                paymentMethod = "01,PPSB,PPS";
            }
            
            if (paymentMethod != "") { 
                HttpUtils.post({
                    url: UrlUtils.PAYMENT_CREATE,
                    params: {
                        transNo: transactionData.transactionid,
                        payMethod: paymentMethod,
                        payAmount: totalAmount,
                        appIdList: location.state?.appIdList ?? [],
                        webtoken: transactionData.webtoken
                    },
                    onSuccess: function (responData) {
                        localStorage.removeItem("paymentId");
                        localStorage.setItem("paymentId", responData.id)
                        setOnPayment(false)
                        navigate(page, stateParams);
                    }
                });
            }

            // For testing
            // if (paymentMethod != "") { 
            //     HttpUtils.post({
            //         url: UrlUtils.PAYMENT_CREATE,
            //         params: {
            //             transNo: "test0002",
            //             payMethod: paymentMethod,
            //             payAmount: totalAmount,
            //             appIdList: location.state?.appIdList ?? [],
            //             webtoken: "test000234123412341234123412354212312412341234124123124124124123124123124124"

            //         },
            //         onSuccess: function (responData) {
            //             localStorage.removeItem("paymentId");
            //             localStorage.setItem("paymentId", responData.id)
            //             navigate(page, stateParams);
            //         }
            //     });
            // }
        }
    }, [afterConfirmPayment]);

    const getAvailablePayment = () =>{
        HttpUtils.post({
            url: UrlUtils.PAYMENT_AVAILABLE_PAYMENT,
            params: {
                "locale": locale === 'en' ?local.en:locale === 'zh-HK' ?local.zh:local.cn,
                "amount": totalAmount,
                // "eserviceids": [
                //     "<eserviceid>", "<eserviceid>"
                // ],
                "preferpaymentmethods": preferpaymentmethods
            },
            onSuccess: (responseData) => {
                let availableMethods = responseData.availablepaymentmethods;
                setAvailableMethods(availableMethods);
                HttpUtils.get({
                    url: UrlUtils.PAYMENT_LIMIT_SETTING_LIST,
                    params: {},
                    onSuccess: (responseData) => {
                        // console.log(responseData)
                        setPaymentLimit(responseData)
        
                    },
                    onError: () =>{
                        // setOnReady(true)
                    }
                });
            },
            onError: () =>{
                setOnReady(true)
            }
        });
        
        HttpUtils.get({
            url: UrlUtils.PAYMENT_LIMIT_SETTING_LIST,
            params: {},
            onSuccess: (responseData) => {
                // console.log(responseData)
                setPaymentLimit(responseData)

            },
            onError: () =>{
                // setOnReady(true)
            }
        });

        // const responseData = {
        //     "availablepaymentmethods": [
        //         {
        //             "active": "Y",
        //             "code": "04,BCFP,FPS",
        //             "pointstonote": [
        //                 {
        //                     "content": "Please take note of the transaction reference number or PRINT this page for making enquiry on the payment status when necessary.",
        //                     "order": 10,
        //                     "type": "INFO"
        //                 },
        //                 {
        //                     "content": "After pressing the 'Pay' button, please DO NOT leave this e-service until you receive the acknowledgement page, otherwise your transaction may not be successful.",
        //                     "order": 11,
        //                     "type": "INFO"
        //                 }
        //             ],
        //             "subtype": "FPS"
        //         },
        //         {
        //             "active": "Y",
        //             "code": "02,BCMP,CreditCard",
        //             "pointstonote": [
        //                 {
        //                     "content": "Please take note of the transaction reference number or PRINT this page for making enquiry on the payment status when necessary.",
        //                     "order": 10,
        //                     "type": "INFO"
        //                 },
        //                 {
        //                     "content": "After pressing the 'Pay' button, please DO NOT leave this e-service until you receive the acknowledgement page, otherwise your transaction may not be successful.",
        //                     "order": 11,
        //                     "type": "INFO"
        //                 },
        //                 {
        //                     "content": "Merchant Name is applicable to credit card payment method only.",
        //                     "order": 40,
        //                     "type": "INFO"
        //                 },
        //                 {
        //                     "content": "Under exceptional conditions, a refund may need to be arranged.  If the payment is made by Credit Card, the refund can normally be made to the Credit Card account that is used for the payment.",
        //                     "order": 41,
        //                     "type": "INFO"
        //                 },
        //                 {
        //                     "content": "Some users may receive an error page or have to wait for several minutes before they get a response from the credit card payment gateway. If you experience such a problem, please wait a moment and retry, or change to use other available payment methods. We apologise for any inconvenience caused.",
        //                     "order": 42,
        //                     "type": "INFO"
        //                 },
        //                 {
        //                     "content": "Different credit card issuers may have implemented different mechanisms to authenticate the cardholder's identity during online payment. Please contact your card issuer if you want to learn more about the J/Secure, MasterCard SecureCode and Verified by Visa service. ",
        //                     "order": 43,
        //                     "type": "INFO"
        //                 }
        //             ],
        //             "subtype": "CreditCard",
        //             "supportedcard": [
        //                 "JCB",
        //                 "MasterCard",
        //                 "Visa"
        //             ]
        //         },
        //         {
        //             "active": "Y",
        //             "code": "03,BCMP,CreditCard",
        //             "pointstonote": [
        //                 {
        //                     "content": "Please take note of the transaction reference number or PRINT this page for making enquiry on the payment status when necessary.",
        //                     "order": 10,
        //                     "type": "INFO"
        //                 },
        //                 {
        //                     "content": "After pressing the 'Pay' button, please DO NOT leave this e-service until you receive the acknowledgement page, otherwise your transaction may not be successful.",
        //                     "order": 11,
        //                     "type": "INFO"
        //                 },
        //                 {
        //                     "content": "Merchant Name is applicable to credit card payment method only.",
        //                     "order": 40,
        //                     "type": "INFO"
        //                 },
        //                 {
        //                     "content": "Under exceptional conditions, a refund may need to be arranged.  If the payment is made by Credit Card, the refund can normally be made to the Credit Card account that is used for the payment.",
        //                     "order": 41,
        //                     "type": "INFO"
        //                 },
        //                 {
        //                     "content": "Some users may receive an error page or have to wait for several minutes before they get a response from the credit card payment gateway. If you experience such a problem, please wait a moment and retry, or change to use other available payment methods. We apologise for any inconvenience caused.",
        //                     "order": 42,
        //                     "type": "INFO"
        //                 },
        //                 {
        //                     "content": "Different credit card issuers may have implemented different mechanisms to authenticate the cardholder's identity during online payment. Please contact your card issuer if you want to learn more about the J/Secure, MasterCard SecureCode and Verified by Visa service. ",
        //                     "order": 43,
        //                     "type": "INFO"
        //                 }
        //             ],
        //             "subtype": "CreditCard",
        //             "supportedcard": [
        //                 "UnionPay"
        //             ]
        //         },
        //         {
        //             "active": "Y",
        //             "code": "01,PPSB,PPS",
        //             "pointstonote": [
        //                 {
        //                     "content": "Please take note of the transaction reference number or PRINT this page for making enquiry on the payment status when necessary.",
        //                     "order": 10,
        //                     "type": "INFO"
        //                 },
        //                 {
        //                     "content": "After pressing the 'Pay' button, please DO NOT leave this e-service until you receive the acknowledgement page, otherwise your transaction may not be successful.",
        //                     "order": 11,
        //                     "type": "INFO"
        //                 },
        //                 {
        //                     "content": "PPS Shop&Buy (PPS) does not support payment via browsers of mobile devices (including mobile phones and tablets) at the moment. If you wish to pay by PPS, please change to use desktop computer. ",
        //                     "order": 21,
        //                     "type": "INFO"
        //                 }
        //             ],
        //             "subtype": "PPS"
        //         }
        //     ]
        // };
        // let availableMethods = responseData.availablepaymentmethods;
        // setAvailableMethods(availableMethods);
    }

    useEffect(() => {
        // console.log(availableMethods)
        if (availableMethods.length > 0) {
            availableMethods.forEach((method) => {
                if (method.subtype === "FPS") {
                    if (totalAmount<1){
                        // method["minLimit"] = true
                        setFPSStatus(method)
                    }
                    else if (totalAmount>9999999.99){
                        // method["maxLimit"] = true
                        setFPSStatus(method)
                    } else {
                        // method["minLimit"] = true
                        // method["maxLimit"] = true
                        // console.log(method) 
                        setFPSStatus(method)
                    }
                } else if (method.subtype === "CreditCard") {
                    method.supportedcard.forEach((supportedcard) => {
                        if (supportedcard === "JCB" || supportedcard === "MasterCard" || supportedcard === "Visa") {
                            setCreditCardStatus(method)
                        } else {
                            if (supportedcard === "UnionPay") {
                                setUnionPayStatus(method)
                            }
                        }
                    })
                } else if (method.subtype === "PPS") {
                    setPPSStatus(method)
                }
            });
            setOnReady(true)
        }
    }, [availableMethods]);

    const getTransactionId = () => {
        HttpUtils.get({
            url: UrlUtils.PAYMENT_TRANSACTION_ID,
            onSuccess: (responseData) => {
                // const transactionData = responseData;
                setTransactionData(responseData)
            }
        });
    }

    // useEffect(() => {
    //     if (availableMethods.length > 0 && Object.keys(transactionData).length > 0) {
    //         setOnReady(true)
    //     }
    // }, [transactionData, availableMethods]);

    const getAppList = () => {
        HttpUtils.post({
            url: UrlUtils.PAYMENT_APP_LIST,
            params: {
                appIds: appIds
            },
            onSuccess: (responseData) => {
                setItemList(responseData)
            }
        });
    }

    // const selectedPaymentMethodHandle = (method) => () => {
    //     setSelectedPaymentMethod(method);
    // };

    // const confirmPaymentHandle = () => () => {
    useEffect(() => {
        if (confirmPayment){
            HttpUtils.post({
                url: UrlUtils.POST_CHECK_APP_EXPRITY_DATE,
                params: {
                    ids: appIds
                },
                onSuccess: (responData) => {
                    if (responData.success == true) {
                        setAfterConfirmPayment(true);
                        return;
                    }
                    let str = "";
                    responData.msg.forEach((item) => {
                        str += "App: " + item.appNo + ", 到期日: " + DateUtils.datetimeStr_Cht(item.expiryDate) + "\n";
                    });
                    setExpiryDateErrText(str.split('\n').map(str => <>{str}<br/></>));
                    setExpiryDateErr(true);
                }
            });
        }
    }, [confirmPayment]);

    const getMethodImgClass = (method) => {
        return selectedPaymentMethod == method || selectedPaymentMethod == "" ? "" : "grayscale";
    }

    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={{ pt: 2 }}>
                            <FormattedMessage id="publicNoticePayment"/>
                        </Typography>
                    </Stack>
                </div>
            </Grid>
            {/*row 1*/}
            <Grid item xs={12} md={12} width="100%">
                <Grid container justifyContent="center" spacing={2} sx={{ p: 2 }} alignitems="stretch" >
                    <Grid item xs={12} md={11} style={{ height: '100%' }}>
                        <Box xs={12} md={12} sx={{ p: 4, border: '3px solid #eee', borderRadius: '10px' }} >
                            <DataGrid
                                recordList={itemList}
                            />
                        </Box>
                    </Grid>
                </Grid>
            </Grid>
            <Grid item xs={12} md={12} width="100%">
                <Stack direction="row" justifyContent="flex-end" alignItems="flex-start" spacing={2} mr={{xs:2,md:12}} >
                    <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                    <Button
                            component="span"
                            variant="contained"
                            // color="error"
                            onClick={() => paymentClick()}
                            sx={{ mt: 4 }}
                        >
                        <FormattedMessage id="pay"/>
                    </Button>
                    <Button
                            component="span"
                            variant="contained"
                            // color="error"
                            onClick={() => { navigate("/publicNotice") }}
                            sx={{ mt: 4 }}
                        >
                        <FormattedMessage id="cancel"/>
                    </Button>
                    </ThemeProvider>
                </Stack>
            </Grid>
            {/*row 2*/}
            <div>
                <Dialog
                    open={expiryDateErr}
                    onClose={() => setExpiryDateErr(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="h2" style={{ padding: '16px' }}>
                        <FormattedMessage id ="MSG.actionFail"/>
                    </Typography>
                    <DialogContent style={{ display: 'flex', }}>
                        <Stack direction="column" justifyContent="space-between">
                            {
                                expiryDateErrText
                            }
                        </Stack>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={() => setExpiryDateErr(false)}><Typography variant="h5">
                            <FormattedMessage id="close"/>
                        </Typography></Button>
                    </DialogActions>
                </Dialog>
            </div>
            <MultiPaymentWindow open={open}
                setOpen={setOpen}
                availableMethods={availableMethods}
                paymentLimit={paymentLimit}
                transactionData={transactionData}
                totalAmount={totalAmount}
                fpsStatus={fpsStatus}
                creditCardStatus={creditCardStatus}
                unionPayStatus={unionPayStatus}
                ppsStatus={ppsStatus}
                setSelectedPaymentMethod={setSelectedPaymentMethod}
                selectedPaymentMethod={selectedPaymentMethod}
                setConfirmPayment={setConfirmPayment}
                getMethodImgClass = {getMethodImgClass}
                onReady = {onReady}
                locale = {locale}
                isFullScreen={isFullScreen}
                appIds={appIds}
                // appNo={itemList.appNo}
                browserType={browserType}
                onPayment={onPayment}
            />
        </Grid >
    );
}

export default Index;