// material-ui
import * as React from 'react';
import * as DateUtils from "utils/DateUtils";
import {PAYMENT_GFMIS_LIST} from "utils/ApiPathConst";
// import * as HttpUtils from "utils/HttpUtils";
import * as FormatUtils from "utils/FormatUtils"
// 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, selectedIds = [], onSelectionChange,}) {
    const [_searchCriteria, set_searchCriteria] = React.useState(searchCriteria);
    
    // const navigate = useNavigate()

    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 selectedIdsRef = React.useRef(selectedIds);
    React.useEffect(() => {
        selectedIdsRef.current = selectedIds;
    }, [selectedIds]);

    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);
            },
        },
        {
            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: 'payMethod',
            headerName: 'Payment Method',
            flex: 1,
            width: 150,
            renderCell: (params) => {
                return getPaymentMethodByCode(params?.value);
            }
        },
        {
            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={60}
                columns={columns}
                height={500} 
                autoHeight={false}
                pagination={false}
                applyGridOnReady={applyGridOnReady}
                applySearch={applySearch}

                checkboxSelection
                disableRowSelectionOnClick
                rowSelectionModel={selectedIds}
                onRowSelectionModelChange={(ids) => onSelectionChange?.(ids)}

                doLoad={React.useMemo(() => ({
                    url: PAYMENT_GFMIS_LIST,
                    params: _searchCriteria,
                    callback: (responseData) => {
                        const newIds = (responseData?.records ?? []).map(r => r.id);
                        const currentSelected = selectedIdsRef.current;

                        if (newIds.length === 0) {
                        onSelectionChange?.([]);
                        return;
                        }

                        if (!currentSelected || currentSelected.length === 0) {
                        onSelectionChange?.(newIds);
                        } else {
                        const stillValid = currentSelected.filter(id => newIds.includes(id));
                        onSelectionChange?.(stillValid);
                        }
                    }
                }), [_searchCriteria])}
            />
        </div>
    );
}
