// material-ui
import * as React from 'react';
import * as DateUtils from "utils/DateUtils";
import {PAYMENT_LIST, PAYMENT_BIB} from "utils/ApiPathConst";
import * as HttpUtils from "utils/HttpUtils";
import * as FormatUtils from "utils/FormatUtils"
import * as PaymentStatus from "utils/statusUtils/PaymentStatus"
import { useNavigate } from "react-router-dom";
import { FiDataGrid } from "components/FiDataGrid";
import { clickableLink } from 'utils/CommonFunction';
import { getPaymentMethodByCode} from "auth/utils";

import {
    Checkbox,
    Dialog, DialogTitle, DialogContent, DialogActions,
    Button,Typography
    // MenuItem
} from '@mui/material';
// ==============================|| EVENT TABLE ||============================== //

export default function SearchPaymentTable({ searchCriteria, applyGridOnReady, applySearch}) {
    const [_searchCriteria, set_searchCriteria] = React.useState(searchCriteria);
    const navigate = useNavigate()
    const [isPopUp, setIsPopUp] = React.useState(false);
    const [bibId, setBibId] = React.useState();
    const [bib, setBib] = React.useState();
    const [appNo, setAppNo] = React.useState();
    const [refreshTrigger, setRefreshTrigger] = React.useState(0);

    const forceRefresh = () => {
        setRefreshTrigger(prev => prev + 1);
    };

    const _sx = {
        padding: "4 2 4 2",
        boxShadow: 1,
        border: 1,
        borderColor: '#DDD',
        '& .MuiDataGrid-cell': {
            borderTop: 1,
            borderBottom: 1,
            borderColor: "#EEE"
        },
        '& .MuiDataGrid-footerContainer': {
            border: 1,
            borderColor: "#EEE"
        }
    }

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

    const handleEditClick = (params) => () => {
        navigate('/paymentPage/details/' + params.row.id);
    };

    const doBIB = () => {
        setIsPopUp(false);
        // console.log(refreshTrigger)
        HttpUtils.post({
            url: PAYMENT_BIB + "/" + bibId,
            onSuccess: function () {
                forceRefresh()
            }
        });
    }
    
    const popUPBib = (id, bibFlag, appNo) => {
        setBibId(id)
        setBib(bibFlag)
        setAppNo(appNo)
        setIsPopUp(true);
    }

    const columns = [
        {
            id: 'appNos',
            field: 'appNos',
            headerName: 'Application No.',
            flex: 1,
            minWidth: 150,
            renderCell: (params) => {
                let appNo = params.row.appNos;
                return <div style={{ marginTop: 2, marginBottom: 2 }}>{appNo}</div>
            },
        },
        {
            field: 'actions',
            headerName: 'Transaction No.',
            flex: 1,
            minWidth: 200,
            cellClassName: 'actions',
            renderCell: (params) => {
                return clickableLink('/paymentPage/details/' + params.row.id, params.row.transNo);
            },
        },
        {
            field: 'payMethod',
            headerName: 'Payment Method',
            flex: 1,
            width: 150,
            renderCell: (params) => {
                return getPaymentMethodByCode(params?.value)
            }
        },
        {
            id: 'transDateTime',
            field: 'transDateTime',
            headerName: 'Transaction Date',
            flex: 1,
            minWidth: 150,

            // sorting/filtering uses this value
            valueGetter: (params) => DateUtils.toDate(params?.value),

            // display uses this (params.value is the *Date* returned above)
            valueFormatter: (params) => {
                const d = params.value;               // Date or Invalid Date
                return d instanceof Date && !isNaN(d.getTime())
                ? DateUtils.dateStr(d)
                : "";
            },

            // make sorting 100% deterministic
            sortComparator: (v1, v2) => {
                const t1 = v1 instanceof Date && !isNaN(v1.getTime()) ? v1.getTime() : -Infinity;
                const t2 = v2 instanceof Date && !isNaN(v2.getTime()) ? v2.getTime() : -Infinity;
                return t1 - t2;
            }
        },
        {
            field: 'bib',
            headerName: 'BIB',
            width: 150,
            renderCell: (params) => {
                return <Checkbox checked={params.row.bib} onChange={() => {popUPBib(params.row.id, params.row.bib, params.row.appNos)}}/>;
            }
        },
        {
            field: 'action',
            headerName: 'Status',
            width: 150,
            renderCell: (params) => {
                return PaymentStatus.getStatus_Eng(params);
            }
        },
        {
            id: 'payAmount',
            field: 'payAmount',
            headerName: 'Amount ($)',
            width: 150,
            valueGetter: (params) => {
                return (params?.value) ? "$ " + FormatUtils.currencyFormat(params?.value) : "";
            }
        },
    ];

    return (
        <div style={{ width: '100%' }}>
            <FiDataGrid
                sx={_sx}
                rowHeight={80}
                columns={columns}
                customPageSize={10}
                onRowDoubleClick={handleEditClick}
                applyGridOnReady={applyGridOnReady}
                applySearch={applySearch}
                // doLoad={{
                //     url:PAYMENT_LIST,
                //     params:_searchCriteria,
                // }}
                doLoad={React.useMemo(() => ({
                    url: PAYMENT_LIST,
                    params: _searchCriteria,
                }), [_searchCriteria, refreshTrigger])}
            />
            <div>
                <Dialog
                    open={isPopUp}
                    onClose={() => setIsPopUp(false)}
                    PaperProps={{
                        sx: {
                            minWidth: '40vw',
                            maxWidth: { xs: '90vw', s: '90vw', m: '70vw', lg: '70vw' },
                            maxHeight: { xs: '90vh', s: '70vh', m: '70vh', lg: '60vh' }
                        }
                    }}
                >
                    <DialogTitle>Bank-in-bank</DialogTitle>
                    <DialogContent style={{ display: 'flex', }}>
                        <Typography variant="h5" style={{ padding: '16px' }}>{bib?"Cancel Bank-in-bank?":"Set "+appNo+" as Bank-in-bank?"}</Typography>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={() => setIsPopUp(false)}><Typography variant="h5">Cancel</Typography></Button>
                        <Button onClick={() => doBIB()}><Typography variant="h5">Confirm</Typography></Button>
                    </DialogActions>
                </Dialog>
            </div>
        </div>
    );
}
