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

import Loadable from 'components/Loadable';
const LoadingComponent = Loadable(React.lazy(() => import('pages/extra-pages/LoadingComponent')));
const PaymentDetails = Loadable(React.lazy(() => import('./PaymentDetails')));
const DataGrid = Loadable(React.lazy(() => import('./DataGrid')));
import ForwardIcon from '@mui/icons-material/Forward';
import titleBackgroundImg from 'assets/images/dashboard/gazette-bar.png'
import {FormattedMessage,useIntl} from "react-intl";
import usePageTitle from "components/usePageTitle";
const BackgroundHead = {
    backgroundImage: `url(${titleBackgroundImg})`,
    width: '100%',
    height: '100%',
    backgroundSize: 'contain',
    backgroundRepeat: 'no-repeat',
    backgroundColor: '#0C489E',
    backgroundPosition: 'right'
}

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

const Index = () => {
    usePageTitle("payDetail");
    
    const params = useParams();
    const navigate = useNavigate()
    const intl = useIntl();
    const [responeData, setResponeData] = React.useState({});
    const [transactionData, setTransactionData] = React.useState({});

    const [record, setRecord] = React.useState({});
    const [itemList, setItemList] = React.useState([]);
    const [onReady, setOnReady] = React.useState(false);
    const [onDownload, setOnDownload] = React.useState(false);
    // const [detailsOrder, setDetailsOrder] = React.useState(2);
    const { locale } = intl;

    React.useEffect(() => {
        loadForm();
        // window.addEventListener('resize', handleResize)
    }, []);

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

    // const handleResize = () => {
    //     setDetailsOrder(window.innerWidth > 1023 ? 2 : -1);
    // }

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


    const loadForm = () => {
        if (params.id > 0) {
            HttpUtils.get({
                url: UrlUtils.PAYMENT_LOAD + "/" + params.id,
                onSuccess: (responseData) => {
                    if (!responseData.data?.id) {
                        navigate("/paymentPage/search");
                    }
                    if(responseData.data.status==null||responseData.data.status=="INPR"){
                        HttpUtils.post({
                            url: UrlUtils.PAYMENT_RETRY_STATUS_API,
                            params:{  
                                "paymentId": params.id
                            },
                            onSuccess: function(responseData2){
                                responseData2.data["transDateStr"] = responseData2.data.transDateTime;
                                responseData2.data["transTimeStr"] = DateUtils.dateFormat(responseData2.data.transDateTime, "HH:mm:ss");
                                setResponeData(responseData2.transactionData)
                                setItemList(responseData2.paymentItemList)
                                setRecord(responseData2.data);
                            },
                            onError: function(){
                                responseData.data["transDateStr"] = responseData.data.transDateTime;
                                responseData.data["transTimeStr"] = DateUtils.dateFormat(responseData.data.transDateTime, "HH:mm:ss");
                                setResponeData(responseData)

                            }
                        });
                    }else{
                        responseData.data["transDateStr"] = responseData.data.transDateTime;
                        responseData.data["transTimeStr"] = DateUtils.dateFormat(responseData.data.transDateTime, "HH:mm:ss");
                        setResponeData(responseData)
                        setItemList(responseData.paymentItemList)
                        setRecord(responseData.data);
                    }
                }
            });
        }
    }

    return (
        !onReady ?
            <Grid container sx={{ minHeight: '87vh', mb: 3 }} direction="column" justifyContent="center" alignItems="center">
                <Grid item>
                    <LoadingComponent />
                </Grid>
            </Grid>
            :
            (
                <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 component="h1" ml={15} color='#FFF' variant="h4" sx={{ pt: 2 }}>
                                        <FormattedMessage id="payDetail"/>
                                    </Typography>
                                </Stack>
                            </div>
                        </Grid>
                        <Grid item xs={12} width={{xs:"90%", sm:"90%", md:"90%", lg:"80%"}}>
                            <Button
                                aria-label={intl.formatMessage({id: 'back'})}
                                title={intl.formatMessage({id: 'back'})}
                                sx={{ ml: 0, mt: 2.5 }} style={{ border: '2px solid' }} variant="outlined" onClick={() => { navigate(-1) }}
                            >
                                <ForwardIcon style={{ height: 30, width: 50, transform: "rotate(180deg)" }} />
                            </Button>
                        </Grid>
                        {/*row 1*/}
                        <Grid item xs={12} md={12} sx={{ textAlign: "center" }}>
                            <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={record}
                                            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>

            )


    );
};

export default Index;
