// material-ui
import * as React from 'react';
import {
    Stack,
    Typography,
    Button,
    Autocomplete,
    TextField,
    Grid,
    Dialog, DialogTitle, DialogContent, DialogActions, useMediaQuery,
} from '@mui/material';
import { FiDataGrid } from "components/FiDataGrid";
import * as HttpUtils from "utils/HttpUtils"
import * as utils from "auth/utils"
import {
    PAYMENT_CHECK,
    POST_CHECK_APP_EXPRITY_DATE,
    GET_PUBLIC_NOTICE_LIST_ListByStatus_pendingPayment_careOfCombo
} from "utils/ApiPathConst"
import * as DateUtils from "utils/DateUtils"
import * as FormatUtils from "utils/FormatUtils"
import * as StatusUtils from "utils/statusUtils/PublicNoteStatusUtils";
import { useNavigate } from "react-router-dom";
import {
    isORGLoggedIn,
    isDummyLoggedIn,
} from "utils/Utils";
// import { dateStr } from "utils/DateUtils";
import { ThemeProvider, useTheme } from "@emotion/react";
import { PNSPS_BUTTON_THEME } from "../../../themes/buttonConst";
import { FormattedMessage, useIntl } from "react-intl";
import { PRIMARY_TEXT_BUTTON_SX, PRIMARY_CONTAINED_BUTTON_SX } from "themes/colorConst";
// ==============================|| EVENT TABLE ||============================== //

export default function SubmittedTab({ setCount, url }) {
    const [rowList, setRowList] = React.useState([]);
    const [selectedRowItems, setSelectedRowItems] = React.useState([]);
    const [isPopUp, setIsPopUp] = React.useState(false);
    const [checkCareOf, setCheckCareOf] = React.useState(false);
    const [careOfComboList, setCareOfComboList] = React.useState([]);
    const [selectedCareOf, setSelectedCareOf] = React.useState(null);
    const [expiryDateErrText, setExpiryDateErrText] = React.useState("");
    const [expiryDateErr, setExpiryDateErr] = React.useState(false);

    const [paymentHoldedErrText, setPaymentHoldedErrText] = React.useState("");
    const [paymentHoldedErr, setPaymentHoldedErr] = React.useState(false);
    const [_searchCriteria, set_searchCriteria] = React.useState({});
    // const [checkPaymentMethod, setCheckPaymentMethod] = React.useState(false);

    const theme = useTheme();
    const isMdOrLg = useMediaQuery(theme.breakpoints.up('md'));
    const intl = useIntl();
    const { locale } = intl;

    //const [amount, setAmount] = React.useState(0);
    const navigate = useNavigate()

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

    React.useEffect(() => {
        if (selectedCareOf != null) {
            set_searchCriteria({ "careOf": selectedCareOf.label });
        } else {
            set_searchCriteria({});
        }
    }, [selectedCareOf]);
    

    const getCareOfList = () => {
        HttpUtils.get({
            url: GET_PUBLIC_NOTICE_LIST_ListByStatus_pendingPayment_careOfCombo,
            params: {},
            onSuccess: function (responData) {
                setCareOfComboList(responData);
            }
        });
    }

    const handleDetailClick = (params) => () => {
        navigate('/publicNotice/' + params.id);
    };

    const renderHeaderWithAria = (params) => (
        <span aria-label={params.colDef.headerName}>{params.colDef.headerName}</span>
    );

    const handlePaymentBtn = () => {
        let appIdList = [];
        let paymentCheckList = [];
        const _datas = rowList;
        const datas = _datas?.filter((row) =>
            selectedRowItems.includes(row.id)
        );
        // console.log(datas)
        for (var i = 0; i < datas?.length; i++) {
            appIdList.push(datas[i].id);
            if ( datas[i].paymentMethod != "online"){
                paymentCheckList.push(datas[i].paymentMethod)
            }
        }
        // console.log(paymentCheckList)
        if(paymentCheckList.length == 0){
            if (appIdList.length < 1) {
                setExpiryDateErrText(intl.formatMessage({ id: 'MSG.plzSelectApp' }));
                setExpiryDateErr(true);
                return;
            }
            HttpUtils.post({
                url: POST_CHECK_APP_EXPRITY_DATE,
                params: {
                    ids: appIdList
                },
                onSuccess: (responData) => {
                    if (responData.success == true) {
                        // setIsPopUp(true);
                        handlePaymentCheck(appIdList)
                        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);
                }
            });
        } else {
            setExpiryDateErrText(intl.formatMessage({ id: 'MSG.plzonlinePayment' }));
            setExpiryDateErr(true);
            return;
        }
    };

    const handlePaymentCheck = (appIdList) => {
        HttpUtils.post({
            url: PAYMENT_CHECK,
            params: {
                appIds: appIdList
            },
            onSuccess: (responseData) => {
                const latestData = {};

                responseData.forEach(item => {
                    // console.log(item)
                const { appId, timeDiff } = item;
                if (latestData[appId] === undefined || timeDiff < latestData[appId].timeDiff) {
                    latestData[appId] = item;
                }
                });
                const latestDataObjects = Object.values(latestData);
                
                const filteredData = latestDataObjects.filter(item => item.timeDiff > 30 || item.status == "CANC" || item.status == "REJT");
                const filteredAppIds = filteredData.map(item => item.appId);

                const appIdsNotInData = appIdList.filter(appId => !latestDataObjects.some(item => item.appId === appId));
                const combinedAppIdsArray = [...appIdsNotInData, ...filteredAppIds];

                const readyToPayment = appIdList.every(appId => combinedAppIdsArray.includes(appId));
                if (readyToPayment) {
                    setIsPopUp(true);
                    return;
                } else {
                    const appIdsInData = appIdList.filter(appId => !combinedAppIdsArray.some(item => item === appId));
                    const HoldingApplication = latestDataObjects.filter(item => appIdsInData.includes(item.appId));
                    const resultString = HoldingApplication.map(item => item.appNo).join(' , ');
                    setPaymentHoldedErrText(resultString);
                    // setPaymentHoldedErrText(intl.formatMessage({ id: 'MSG.paymentHolded' }, { appNo: record.appNo }));
                    setPaymentHoldedErr(true);
                }
            }
        });
    };

    const columns = [
        {
            id: 'appNo',
            field: 'appNo',
            headerName: intl.formatMessage({ id: 'applicationId' }),
            width: isMdOrLg ? 'auto' : 160,
            flex: isMdOrLg ? 1 : undefined,
            renderHeader: renderHeaderWithAria,
        },
        {
            id: 'created',
            field: 'created',
            headerName: intl.formatMessage({ id: 'submitDate' }),
            width: isMdOrLg ? 'auto' : 160,
            flex: isMdOrLg ? 1 : undefined,
            renderHeader: renderHeaderWithAria,
            valueGetter: (params) => {
                return DateUtils.datetimeStr(params.value);
            }
        },
        {
            id: 'remarks',
            field: 'remarks',
            headerName: isORGLoggedIn() ? intl.formatMessage({ id: 'gazetteCount2_1' }) : intl.formatMessage({ id: 'myRemarks' }),
            width: isMdOrLg ? 'auto' : 400,
            flex: isMdOrLg ? 3 : undefined,
            renderHeader: renderHeaderWithAria,
            renderCell: (params) => (
                isORGLoggedIn() ?
                        isDummyLoggedIn()?
                        <div>
                            <FormattedMessage id="gazetteCount" />: {params.row.issueVolume + "/" + params.row.issueYear
                                + " No. " + params.row.issueNo}<br />
                            GLD: {params.row.custName} <br />
                            <FormattedMessage id="careOf" />: {params.row.careOf} <br />
                            <FormattedMessage id="myRemarks" />: {params.row.remarks}
                        </div>:
                        <div>
                            <FormattedMessage id="gazetteCount" />: {params.row.issueVolume + "/" + params.row.issueYear
                                + " No. " + params.row.issueNo}<br />
                            <FormattedMessage id="careOf" />: {params.row.careOf} <br />
                            <FormattedMessage id="myRemarks" />: {params.row.remarks}
                        </div> 
                    :
                    <div>
                        <FormattedMessage id="gazetteCount" />: {params.row.issueVolume + "/" + params.row.issueYear
                            + " No. " + params.row.issueNo}<br />
                        <FormattedMessage id="myRemarks" />:{params.row.remarks}
                    </div>
            )
        },
        {
            id: 'fee',
            field: 'fee',
            headerName: intl.formatMessage({ id: 'price' }),
            width: isMdOrLg ? 'auto' : 160,
            flex: isMdOrLg ? 1 : undefined,
            renderHeader: renderHeaderWithAria,
            renderCell: (params) => {
                return FormatUtils.currencyFormat(params.row.fee)
            },
        },
        {
            id: 'paymentMethodAndDeadLine',
            field: 'paymentMethodAndDeadLine',
            headerName: intl.formatMessage({ id: 'paymentMethodAndDeadLine' }),
            renderHeader: renderHeaderWithAria,
            width: isMdOrLg ? 'auto' : 250,
            flex: isMdOrLg ? 2 : undefined,
            renderCell: (params) => (
                <div>
                    <FormattedMessage id={utils.getPaymentMethod(params.row.paymentMethod)} /><br />
                    <div>
                        {/* {dateStr(params.row.closingDate)} */}
                        {
                            DateUtils.is18_00(params.row.expiryDate) ?
                            DateUtils.formatDateForLocale(params.row.expiryDate, intl, locale):
                                params.row.paymentMethod=="online"?
                                    locale === 'en' ?
                                        `${DateUtils.dateFormatWithFix(params.row.expiryDate, intl.formatMessage({ id: "datetimeFormate" }), 14, 30)?.replace("am", "a.m.")?.replace("pm", "p.m.")}`
                                        :
                                        `${DateUtils.dateFormatWithFix(params.row.expiryDate, intl.formatMessage({ id: "datetimeFormate" }), 14, 30)?.replace("am", "上午")?.replace("pm", "下午").replace("00分", "")}`
                                    :params.row.paymentMethod=="demandNote" ?
                                        locale === 'en' ?
                                            `${DateUtils.dateFormatWithFix(params.row.expiryDate, intl.formatMessage({ id: "datetimeFormate" }), 12, 0)?.replace("am", "a.m.")?.replace("pm", "p.m.")}`
                                            :
                                            `${DateUtils.dateFormatWithFix(params.row.expiryDate, intl.formatMessage({ id: "datetimeFormate" }), 12, 0)?.replace("am", "上午")?.replace("pm", "下午").replace("00分", "")}`
                                        :
                                            locale === 'en' ?
                                                    `${DateUtils.dateFormatWithFix(params.row.expiryDate, intl.formatMessage({ id: "datetimeFormate" }), 12, 30)?.replace("am", "a.m.")?.replace("pm", "p.m.")}`
                                                    :
                                                    `${DateUtils.dateFormatWithFix(params.row.expiryDate, intl.formatMessage({ id: "datetimeFormate" }), 12, 30)?.replace("am", "上午")?.replace("pm", "下午").replace("00分", "")}`
                        }
                        {/* {
                            locale === 'en' ?
                                `${DateUtils.dateFormatWithFix(params.row.closingDate, intl.formatMessage({ id: "datetimeFormate" }), 14, 30)?.replace("am", "a.m.")?.replace("pm", "p.m.")}`
                                :
                                `${DateUtils.dateFormatWithFix(params.row.closingDate, intl.formatMessage({ id: "datetimeFormate" }), 14, 30)?.replace("am", "上午")?.replace("pm", "下午").replace("00分", "")}`
                        }
                        {params.row.paymentMethod=="online" ? " 2:30pm"
                            :params.row.paymentMethod=="demandNote" ? " 12:00pm"
                                : " 12:30pm"} */}
                    </div>
                </div>
            )
        },
        // {
        //     id: 'closingDateOff',
        //     field: 'closingDateOff',
        //     headerName: intl.formatMessage({ id: 'paymentMethod' }),
        //     width: isMdOrLg ? 'auto' : 160,
        //     flex: isMdOrLg ? 1 : undefined,
        //     renderCell: (params) => {
        //         // console.log(params)
        //         let closingDateOff = params.row.closingDateOff;
        //         return <div style={{ margin: 4 }}>{dateStr(closingDateOff)}</div>
        //     },
        // },
        {
            id: 'status',
            field: 'status',
            headerName: intl.formatMessage({ id: 'status' }),
            width: isMdOrLg ? 'auto' : 160,
            flex: isMdOrLg ? 1 : undefined,
            renderHeader: renderHeaderWithAria,
            renderCell: (params) => {
                return StatusUtils.getStatusIntl(params, intl);
            },
        },
        {
            field: 'actions',
            type: 'actions',
            headerName: '',
            width: 150,
            renderHeader: renderHeaderWithAria,
            cellClassName: 'actions',
            renderCell: (params) => {
                return <Button aria-label={intl.formatMessage({ id: 'viewDetail' })} onClick={handleDetailClick(params)} sx={PRIMARY_TEXT_BUTTON_SX}>
                    <FormattedMessage id="viewDetail" />
                </Button>;
            },
        }
    ];

    const getWindowContent = () => {
        var content = [];
        let totalAmount = 0;
        const _datas = rowList;
        const datas = _datas?.filter((row) =>
            selectedRowItems.includes(row.id)
        );
        for (var i = 0; i < datas?.length; i++) {
            content.push(
                <React.Fragment key={datas[i].id}>
                    <Stack direction="row" justifyContent="space-between">
                        <Typography variant="h5">
                            <FormattedMessage id="applicationId" />: {datas[i].appNo}
                        </Typography>
                        ({DateUtils.datetimeStr(datas[i].created)})
                    </Stack>
                    <FormattedMessage id="extraMark" />: {datas[i].remarks}
                    <br /><br />
                </React.Fragment>
            );

            totalAmount += datas[i].fee;
        }
        content.push(
            <Typography key="payment-total" variant="h5">
                <FormattedMessage id="totalAmount" /> ($): {FormatUtils.currencyFormat(totalAmount)}
                <br /><br />
            </Typography>
        );
        return content;
    }

    function handleRowDoubleClick(params) {
        navigate('/publicNotice/' + params.id);
    }

    function doPayment() {
        setIsPopUp(false);
        let totalAmount = 0;
        let appIdList = [];
        const _datas = rowList;
        const datas = _datas?.filter((row) =>
            selectedRowItems.includes(row.id)
        );
        // console.log(datas)
        for (var i = 0; i < datas?.length; i++) {
            totalAmount += datas[i].fee;
            appIdList.push(datas[i].id);
        }
        const firstCareOf = datas[0].careOf;
        const areAllCareOfEqual = datas.every(obj => obj.careOf === firstCareOf);


        if (appIdList.length > 0 && areAllCareOfEqual) {
            navigate('/paymentPage', { state: { amount: totalAmount, appIdList: appIdList } });
        } else {
            setCheckCareOf(true);
            // console.log("The selected applications should be from the same Care of.")
        }
    }

    function afterWarningPayment() {
        let totalAmount = 0;
        let appIdList = [];
        const _datas = rowList;
        const datas = _datas?.filter((row) =>
            selectedRowItems.includes(row.id)
        );
        // console.log(datas)
        for (var i = 0; i < datas?.length; i++) {
            totalAmount += datas[i].fee;
            appIdList.push(datas[i].id);
        }
        navigate('/paymentPage', { state: { amount: totalAmount, appIdList: appIdList } });
    }

    return (
        <>
            <div style={{ minHeight: 400, width: '100%', padding: 4 }}>
                {isORGLoggedIn() ?
                    <Grid container direction="row" justifyContent="flex-start" alignItems="center" >
                        <Grid item xs={3} md={1}>
                            <Typography variant="h5"><FormattedMessage id="careOf" />:</Typography>
                        </Grid>
                        <Grid item xs={8} md={2}>
                            <Autocomplete
                                disablePortal
                                id="careOfCombo"
                                value={selectedCareOf === null ? null : selectedCareOf}
                                options={careOfComboList}
                                getOptionLabel={(option) => {
                                    if (option == null) return "";
                                    if (typeof option === "string") return option;
                                    return option.label != null ? String(option.label) : "";
                                }}
                                onChange={(event, newValue) => {
                                    // console.log(newValue)
                                    setSelectedCareOf(newValue);
                                }}
                                sx={{
                                    '& .MuiInputBase-root': { alignItems: 'center' },
                                    '& .MuiAutocomplete-endAdornment': { top: '50%', transform: 'translateY(-50%)' },
                                    '& .MuiOutlinedInput-root': { height: 40 }
                                }}
                                renderInput={(params) => <TextField {...params} inputProps={{ ...params.inputProps, 'aria-label': intl.formatMessage({ id: 'careOf' }) }} />}
                                clearText={intl.formatMessage({ id: "muiClear" })}
                                closeText={intl.formatMessage({ id: "muiClose" })}
                                openText={intl.formatMessage({ id: "muiOpen" })}
                                noOptionsText={intl.formatMessage({ id: "muiNoOptions" })}
                            />
                        </Grid>
                    </Grid> : null
                }
                <FiDataGrid
                    checkboxSelection
                    disableRowSelectionOnClick
                    columns={columns}
                    customPageSize={10}
                    onRowSelectionModelChange={(newSelection) => {
                        setSelectedRowItems(newSelection);
                    }}
                    onRowDoubleClick={handleRowDoubleClick}
                    getRowHeight={() => 'auto'}
                    doLoad={React.useMemo(() => ({
                        url: url,
                        params: _searchCriteria,
                        callback: function (responseData) {
                            setCount(responseData?.count ?? 0);
                            setRowList(responseData?.records);
                        }
                    }),[url, _searchCriteria])}
                />

                <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                    <Button
                        variant="contained"
                        aria-label={intl.formatMessage({ id: 'payOnlineBtn' })}
                        onClick={() => { handlePaymentBtn() }}
                        sx={{ mt: 2, ml: 1 }}
                    >
                        <FormattedMessage id="payOnlineBtn" />
                    </Button>
                </ThemeProvider>
            </div>

            <div>
                <Dialog
                    open={isPopUp}
                    onClose={() => setIsPopUp(false)}
                    PaperProps={{
                        sx: {
                            minWidth: '40vw',
                            maxWidth: { xs: '90vw', s: '90vw', m: '70vw', lg: '30vw' },
                            maxHeight: { xs: '90vh', s: '70vh', m: '70vh', lg: '50vh' }
                        }
                    }}
                >
                    <DialogTitle>
                        <Typography variant="h3" >
                            <FormattedMessage id="payConfirm" />
                        </Typography>
                    </DialogTitle>
                    <DialogContent style={{ display: 'flex', }}>
                        <Stack direction="column" justifyContent="space-between">
                            {getWindowContent()}
                        </Stack>
                    </DialogContent>
                    <DialogActions>
                        <Button variant="contained" onClick={() => setIsPopUp(false)} aria-label={intl.formatMessage({ id: 'close' })} sx={PRIMARY_CONTAINED_BUTTON_SX}>
                            <Typography variant="h5" sx={{ color: 'inherit' }}>
                                <FormattedMessage id="close" />
                            </Typography></Button>

                        <Button variant="contained" onClick={() => doPayment()} aria-label={intl.formatMessage({ id: 'confirm' })} sx={PRIMARY_CONTAINED_BUTTON_SX}>
                            <Typography variant="h5" sx={{ color: 'inherit' }}>
                                <FormattedMessage id="confirm" />
                            </Typography></Button>
                    </DialogActions>
                </Dialog>
            </div>

            <div>
                <Dialog
                    open={checkCareOf}
                    onClose={() => setCheckCareOf(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="warning" />
                    </Typography>
                    <DialogContent style={{ display: 'flex', }}>
                        <Stack direction="column" justifyContent="space-between">
                            <Typography variant="h5" color="error">
                                <FormattedMessage id="careOfWarning" />
                            </Typography>
                        </Stack>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={() => setCheckCareOf(false)} aria-label={intl.formatMessage({ id: 'close' })}>
                            <Typography variant="h5">
                                <FormattedMessage id="close" />
                            </Typography></Button>

                        <Button onClick={() => afterWarningPayment()} aria-label={intl.formatMessage({ id: 'confirm' })}>
                            <Typography variant="h5">
                                <FormattedMessage id="confirm" />
                            </Typography></Button>
                    </DialogActions>
                </Dialog>
            </div>

            <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="h4" style={{ paddingLeft: '24px' }}><FormattedMessage id="MSG.actionFail" /></Typography>
                    <DialogContent style={{ display: 'flex', }}>
                        <Stack direction="column" justifyContent="space-between">
                            {
                                expiryDateErrText
                            }
                        </Stack>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={() => setExpiryDateErr(false)} aria-label={intl.formatMessage({ id: 'close' })}>
                            <Typography variant="h5">
                                <FormattedMessage id="close" />
                            </Typography></Button>
                    </DialogActions>
                </Dialog>
            </div>
            <div>
                <Dialog
                    open={paymentHoldedErr}
                    onClose={() => setPaymentHoldedErr(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="h4" style={{ paddingLeft: '24px' }}><FormattedMessage id="MSG.actionFail" /></Typography>
                    <DialogContent style={{ display: 'flex', }}>
                        <Stack direction="column" justifyContent="space-between">
                            <div dangerouslySetInnerHTML={{ __html: intl.formatMessage({ id: 'MSG.paymentHolded' }, { appNo: paymentHoldedErrText }) }} />
                        </Stack>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={() => setPaymentHoldedErr(false)} aria-label={intl.formatMessage({ id: 'close' })}>
                            <Typography variant="h5">
                                <FormattedMessage id="close" />
                            </Typography></Button>
                    </DialogActions>
                </Dialog>
            </div>
        </>
    );



}
