// material-ui
import {
    Grid,
    Typography,
    Stack,
    Box
    // Button,
    // FormLabel,
} 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 { paymentPath } from "auth/utils";
import * as DateUtils from "utils/DateUtils"

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

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 [responeData, setResponeDataData] = React.useState({});

    const [paymentData, setPaymentData] = React.useState({});
    const [itemList, setItemList] = React.useState([]);
    // const [paymentId, setPaymentId] = React.useState("");
    const [onDownload, setOnDownload] = React.useState(false);

    const [transactionData, setTransactionData] = React.useState({});
    // const [transactionDate, setTransactionDate] = React.useState("");
    // const [transactionTime, setTransactionTime] = React.useState("");
    const [onReady, setOnReady] = React.useState(false);
    // const updatePaymentApi = "/api/payment/updatepayment";
    // const paymentStatusApi = "/api/payment/status/";
    const intl = useIntl();
    const { locale } = intl;


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

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

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

    const loadForm = () => {
        // const date = new Date();
        // const trnDate = date.getDate() + "/" + date.getMonth() + "/" + date.getFullYear();
        // const trnTime = date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
        // setTransactionDate(trnDate)
        // setTransactionTime(trnTime)
        const params = new URLSearchParams(window.location.search);
        let transactionid = params.get("TRANSACTION_ID")
        let receipt_token = params.get("RECEIPT_TOKEN").replace("%3D", "=")

        HttpUtils.post({
            url: UrlUtils.UPDATE_PAYMENT_API,
            params: {
                "transactionid": transactionid,
                "receipttoken": receipt_token,
            },
            onSuccess: function () {
                //     {
                //         "amount": 999.99,
                //         "currencycode": "HKD",
                //         "paymentdetail": {
                //             "attemptno": 1,
                //             "channel": "MobileWallet",
                //             "paymentid": "C202310268000681",
                //             "paymentmethod": "04",
                //             "result": {
                //                 "canretry": "Y",
                //                 "description": "CANC - Cancelled by user or Payment Server.",
                //                 "paymentstatuscode": "CANC",
                //                 "rejectreasoncode": "Payment Cancelled. [PAY-E-9022]"
                //             },
                //             "subtype": "FPS",
                //             "time": "2023-10-26T09:02:17Z[UTC]"
                //         },
                //         "transactionid": "20231026170103921"
                //     }
                // )

                HttpUtils.post({
                    url: UrlUtils.PAYMENT_CALLBACK_STATUS_API,
                    params: {
                        "apprefid": transactionid,
                        // "webtoken": localStorage.getItem("webtoken"),
                        // "paymentId": localStorage.getItem("paymentId"),
                        "transactionid":Number(transactionid)
                    },
                    onSuccess: function (responseData) {
                        if (responseData.paymentdetail?.result?.paymentstatuscode === "APPR") {
                            localStorage.removeItem("webtoken");
                            localStorage.removeItem("transactionid");
                        }
                        responseData.data["transDateStr"] = responseData.data.transDateTime;
                        responseData.data["transTimeStr"] = DateUtils.dateFormat(responseData.data.transDateTime, "HH:mm:ss");
                        setResponeDataData(responseData.transactionData)
                        setItemList(responseData.paymentItemList)
                        setPaymentData(responseData.data);
                        // if (responseData.paymentdetail?.result?.paymentstatuscode === "APPR") {
                            
                        // }
                        // HttpUtils.post({
                        //     url: UrlUtils.PAYMENT_SAVE,
                        //     params: {
                        //         id: localStorage.getItem("paymentId"),
                        //         transNo: responseData.transactionid,
                        //         transDateTime: new Date(responseData.paymentdetail.time).toISOString(),
                        //         egisRefNo: responseData.paymentdetail.paymentid,
                        //         status: responseData.paymentdetail.result.paymentstatuscode,
                        //         payload: responseData
                        //     },
                        //     onSuccess: function (responseData2) {
                        //         responseData2.data["transDateStr"] = DateUtils.dateFormat(responseData2.data.transDateTime, "DD/MM/YYYY");
                        //         responseData2.data["transTimeStr"] = DateUtils.dateFormat(responseData2.data.transDateTime, "HH:mm:ss");
                        //         setItemList(responseData2.paymentItemList)
                        //         setPaymentData(responseData2.data);
                        //         // localStorage.removeItem("paymentId");
                        //         // setPaymentId(responseData2.id)
                        //     }
                        // });
                    }
                });
            }
        });
    }

    const doPrint = () => {
        // window.print();
        setOnDownload(true)
        const local = locale
        console.log(local)
        HttpUtils.fileDownload({
            // url: UrlUtils.GEN_PAYMENT_RECEIPT+"/"+localStorage.getItem("paymentId")+"/"+local,
            url: UrlUtils.GEN_PAYMENT_RECEIPT+"/"+paymentData.id+"/"+local,
            onResponse:()=>{
                setOnDownload(false)
            },
            onError:()=>{
                setOnDownload(false)
            }
        });
    };

    return (
        !onReady ?
            <Grid container sx={{ minHeight: '87vh', mb: 3 }} direction="column" justifyContent="center" alignItems="center">
                <Grid item>
                    <LoadingComponent />
                </Grid>
            </Grid>
            :
            transactionData.paymentdetail?.result?.paymentstatuscode === "APPR" ?
                (
                    <div>
                        <style>
                            {`@media print {.printHidden{display: none;} .printOrder{order:-1 !important;}`}
                        </style>
                        <Grid container className="printheight" sx={{ minHeight: '80%', backgroundColor: '#fff' }} direction="column" justifyContent="flex-start" alignItems="center">
                            <Grid className="printHidden" 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="publicNoticePaymentSuccess"/>
                                        </Typography>
                                    </Stack>
                                </div>
                            </Grid>
                            {/*row 1*/}
                            <Grid item xs={12} md={12} spacing={2} sx={{ textAlign: "center" }}>
                                <Typography variant="h3" sx={{ ml: 8, mt: 4, mr: 8, textAlign: "center" }}>
                                    <FormattedMessage id="MSG.paymentMsg"/>
                                </Typography>
                                <Grid container justifyContent="center" direction="column" spacing={2} sx={{ p: 2 }} alignitems="stretch" >
                                    <Grid item className="printOrder" xs={12} md={12} sx={{ pt: 2 }} style={{ height: '100%', order: 1 }}>
                                        <Box xs={12} md={12} sx={{ border: '3px solid #eee', borderRadius: '10px' }} >
                                            <PaymentDetails
                                                formData={paymentData}
                                                doPrint={doPrint}
                                                onDownload={onDownload}
                                                style={{
                                                    display: "flex",
                                                    height: "100%",
                                                    flex: 1
                                                }}
                                            />
                                        </Box>
                                    </Grid>
                                    <Grid item xs={12} md={12} sx={{ pt: 1, pb: 2 }} style={{ height: '100%', order: 2 }}>
                                        <Box xs={12} md={12} sx={{ border: '3px solid #eee', borderRadius: '10px' }} >
                                            <DataGrid
                                                recordList={itemList}
                                            />
                                        </Box>
                                    </Grid>
                                </Grid>
                            </Grid>
                            {/*row 2*/}
                        </Grid >
                    </div>
                ) :
                (transactionData.paymentdetail?.result?.paymentstatuscode === "CANC" ?
                    <div>
                        <style>
                            {`@media print {.printHidden{display: none;} .printOrder{order:-1 !important;}`}
                        </style>
                        <Grid container className="printheight" sx={{ minHeight: '80%', backgroundColor: '#fff' }} direction="column" justifyContent="flex-start" alignItems="center" >
                            <Grid className="printHidden" 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="publicNoticePaymentCancel"/>
                                        </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="h5" sx={{ ml: 8, mt: 4, mr: 8, textAlign: "left" }}>
                                                <FormattedMessage id="MSG.paymentCancelMsg1"/>
                                                <br /><br />
                                                <FormattedMessage id="MSG.paymentCancelMsg2"/>
                                                <br /><br />
                                                <FormattedMessage id="MSG.paymentCancelMsg3"/>
                                                <br />
                                                <FormattedMessage id="MSG.paymentCancelMsg4"/>
                                                <br /><br />
                                                <FormattedMessage id="MSG.paymentCancelMsg5"/>
                                                <br />
                                                <FormattedMessage id="MSG.paymentCancelMsg6"/>
                                                <br />
                                                <FormattedMessage id="MSG.paymentCancelMsg7"/>
                                                <br /><br />
                                                <FormattedMessage id="MSG.paymentCancelMsg8"/>
                                            </Typography>
                                        </Grid>
                                    </center>
                                </Grid>
                            </Grid>
                            {/*row 2*/}
                        </Grid >
                    </div>
                    :
                    <div>
                        <style>
                            {`@media print {.printHidden{display: none;} .printOrder{order:-1 !important;}`}
                        </style>
                        <Grid container className="printheight" sx={{ minHeight: '80%', backgroundColor: '#fff' }}direction="column" justifyContent="flex-start" alignItems="center" >
                            <Grid className="printHidden" 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="publicNoticePaymentFail"/>
                                        </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="h5" sx={{ ml: 8, mt: 4, mr: 8, textAlign: "left" }}>
                                                <FormattedMessage id="MSG.paymentFailMsg1"/>
                                                <br /><br />
                                                <FormattedMessage id="MSG.paymentFailMsg2"/>
                                                <br /><br />
                                                <ul>
                                                    <li>
                                                        <FormattedMessage id="MSG.paymentFailMsg3"/>
                                                    </li>
                                                    <li>
                                                        <FormattedMessage id="MSG.paymentFailMsg4"/>
                                                    </li>
                                                    <li>
                                                        <FormattedMessage id="MSG.paymentFailMsg5"/>
                                                    </li>
                                                </ul>
                                                <br /><br />
                                                <FormattedMessage id="MSG.paymentFailMsg6"/>
                                                <br /><br />
                                                <ul>
                                                    <li>
                                                        <FormattedMessage id="MSG.paymentFailMsg7"/>
                                                    </li>
                                                    <li>
                                                        <FormattedMessage id="MSG.paymentFailMsg8"/>
                                                    </li>
                                                    <li>
                                                        <FormattedMessage id="MSG.paymentFailMsg9"/>
                                                    </li>
                                                </ul>
                                                <br /><br />
                                                <FormattedMessage id="MSG.paymentFailMsg10"/>
                                            </Typography> 
                                        </Grid>
                                    </center>
                                </Grid>
                            </Grid>
                            {/*row 2*/}
                        </Grid >
                    </div>
                )
    );
};

export default Index;
