// 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 UrlUtils 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,
} from "utils/Utils";
import {ThemeProvider, useTheme} from "@emotion/react";
import {PNSPS_BUTTON_THEME} from "../../../themes/buttonConst";
import {FormattedMessage, useIntl} from "react-intl";
// ==============================|| EVENT TABLE ||============================== //

export default function SubmittedTab({ rows }) {
    const [rowList, setRowList] = React.useState([]);
    const [selectedRowItems, setSelectedRowItems] = React.useState([]);
    const [isPopUp, setIsPopUp] = React.useState(false);
    const [checkCareOf, setCheckCareOf] = React.useState(false);
    const [getCareOfList, setCareOfList] = React.useState([]);
    const [careOfComboList, setCareOfComboList] = React.useState([{}]);
    const [selectedCareOf, setSelectedCareOf] = React.useState(null);
    const [expiryDateErrText, setExpiryDateErrText] = React.useState("");
    const [expiryDateErr, setExpiryDateErr] = React.useState(false);
    const theme = useTheme();
    const isMdOrLg = useMediaQuery(theme.breakpoints.up('md'));
    const intl = useIntl();

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

    React.useEffect(() => {
        // const careOfList = rows.map(obj => obj.careOf);
        // console.log(rows)
        // console.log(careOfList)
        setRowList(rows)
        const formattedData = Array.from(new Set(rows.filter(obj => obj.careOf !== null).map(obj => obj.careOf))).map((careOf, index) => ({
            key: index,
            id: rows.find(obj => obj.careOf === careOf).id,
            label: careOf
        }));
        //   console.log(formattedData)
        setCareOfList(formattedData)
    }, []);

    React.useEffect(() => {
        // console.log(getCareOfList)
        setCareOfComboList(getCareOfList)
    }, [getCareOfList]);

    React.useEffect(() => {
        if (selectedCareOf != null) {
            const afteSelectedList = [];
            console.log(rows)
            console.log(selectedCareOf)
            rows.forEach((element) => {
                if (element.careOf===selectedCareOf.label){
                    afteSelectedList.push(element)    
                }
            });
            // afteSelectedList.push(rows.find(obj => obj.careOf ===(selectedCareOf.label)));
            console.log(afteSelectedList)
            setRowList(afteSelectedList)
        } else {
            setRowList(rows)
        }
    }, [selectedCareOf]);

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

    const handlePaymentBtn = () => {
        let appIdList = [];
        const datas = rows?.filter((row) =>
            selectedRowItems.includes(row.id)
        );
        // console.log(datas)
        for (var i = 0; i < datas?.length; i++) {
            appIdList.push(datas[i].id);
        }
        HttpUtils.post({
            url: UrlUtils.POST_CHECK_APP_EXPRITY_DATE,
            params: {
                ids: appIdList
            },
            onSuccess: (responData) => {
                if (responData.success == true) {
                    setIsPopUp(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);
            }
        });


    };

    const columns = [
        {
            id: 'appNo',
            field: 'appNo',
            headerName: intl.formatMessage({id: 'applicationId'}),
            width: isMdOrLg ? 'auto' : 160,
            flex: isMdOrLg ? 1 : undefined,
        },
        {
            id: 'created',
            field: 'created',
            headerName: intl.formatMessage({id: 'submitDate'}),
            width: isMdOrLg ? 'auto' : 160,
            flex: isMdOrLg ? 1 : undefined,
            valueGetter: (params) => {
                return DateUtils.datetimeStr(params.value);
            }
        },
        // {
        //     id: 'contactPerson',
        //     field: 'contactPerson',
        //     headerName: '聯絡人',
        //     flex: 2,
        //     renderCell: (params) => {
        //         let phone = JSON.parse(params.row.contactTelNo);
        //         let faxNo = JSON.parse(params.row.contactFaxNo);

        //         let contact = "";
        //         if (phone) {
        //             contact = "電話: " + phone?.countryCode + " " + phone?.phoneNumber
        //         }

        //         if (faxNo && faxNo?.faxNumber) {
        //             if (contact != "")
        //                 contact = contact + ", "
        //             contact = contact + "傳真:" + faxNo?.countryCode + " " + faxNo?.faxNumber
        //         }

        //         return (<>
        //             {params?.value}<br />
        //             {contact}
        //         </>);
        //     }
        // },
        {
            id: 'remarks',
            field: 'remarks',
            headerName: isORGLoggedIn() ? intl.formatMessage({id: 'gazetteCount2_1'}) : intl.formatMessage({id: 'myRemarks'}),
            width: isMdOrLg ? 'auto' : 400,
            flex: isMdOrLg ? 3 : undefined,
            renderCell: (params) => (
                isORGLoggedIn() ?
                    <div>
                        Care Of: {params.row.careOf}<br/>
                        <FormattedMessage id="myRemarks"/>: {params.row.remarks}
                    </div> :
                    <div>
                        {/* <Typography variant="pnspsNormalText"> */}
                            {params.row.remarks}
                            {/* </Typography> */}
                    </div>
            )
        },
        {
            id: 'fee',
            field: 'fee',
            headerName: intl.formatMessage({id: 'price'}),
            width: isMdOrLg ? 'auto' : 160,
            flex: isMdOrLg ? 1 : undefined,
            renderCell: (params) => {
                return FormatUtils.currencyFormat(params.row.fee)
            },
        },
        {
            id: 'status',
            field: 'status',
            headerName: intl.formatMessage({id: 'status'}),
            width: isMdOrLg ? 'auto' : 160,
            flex: isMdOrLg ? 1 : undefined,
            renderCell: (params) => {
                return [StatusUtils.getStatusIntl(params,intl)]
            },
        },
        {
            field: 'actions',
            type: 'actions',
            headerName: '',
            width: 150,
            cellClassName: 'actions',
            renderCell: (params) => {
                return <Button aria-label={intl.formatMessage({id: 'viewDetail'})} onClick={handleDetailClick(params)}>
                    <FormattedMessage id="viewDetail"/>
                </Button>;
            },
        }
    ];

    const getWindowContent = () => {
        var content = [];
        let totalAmount = 0;
        const datas = rows?.filter((row) =>
            selectedRowItems.includes(row.id)
        );
        for (var i = 0; i < datas?.length; i++) {
            content.push(<>
                <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 />
            </>);

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

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

    function doPayment() {
        setIsPopUp(false);
        let totalAmount = 0;
        let appIdList = [];
        const datas = rows?.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 = rows?.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">Care Of:</Typography>
                        </Grid>
                        <Grid item xs={8} md={2}>
                            <Autocomplete
                                disablePortal
                                id="careOfCombo"
                                value={selectedCareOf === null ? null : selectedCareOf}
                                options={careOfComboList}
                                onChange={(event, newValue) => {
                                    // console.log(newValue)
                                    setSelectedCareOf(newValue);
                                }}
                                renderInput={(params) => <TextField {...params} />}
                            />
                        </Grid>
                    </Grid> : null
                }
                <FiDataGrid
                    checkboxSelection
                    disableRowSelectionOnClick
                    rows={rowList}
                    columns={columns}
                    customPageSize={20}
                    onRowSelectionModelChange={(newSelection) => {
                        setSelectedRowItems(newSelection);
                    }}
                    onRowDoubleClick={handleRowDoubleClick}
                    getRowHeight={() => 'auto'}
                />

                <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                <Button
                    color="create"
                    variant="contained"
                    aria-label={intl.formatMessage({id: 'pay'})}
                    onClick={() => { handlePaymentBtn() }}
                    sx={{mt:2, ml:1}}
                >
                    <FormattedMessage id="pay"/>
                </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 onClick={() => setIsPopUp(false)} aria-label={intl.formatMessage({id: 'close'})}>
                            <Typography variant="h5">
                                <FormattedMessage id="close"/>
                            </Typography></Button>

                        <Button onClick={() => doPayment()} aria-label={intl.formatMessage({id: 'confirm'})}>
                            <Typography variant="h5">
                            <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' }}>Warning</Typography>
                    <DialogContent style={{ display: 'flex', }}>
                        <Stack direction="column" justifyContent="space-between">
                            <Typography variant="h5" color="error">
                                You have been selected different Care of applications. Are you want to pay?
                            </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="h2" style={{ padding: '16px' }}>行動失敗</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>
        </>
    );



}
