// material-ui
import * as React from 'react';
import * as DateUtils from "utils/DateUtils";
import * as FormatUtils from "utils/FormatUtils"
import * as ProofStatus from "utils/statusUtils/ProofStatus";
import { LIST_PROOF } from "utils/ApiPathConst";
import { useNavigate } from "react-router-dom";
import { FiDataGrid } from "components/FiDataGrid";
import { clickableLink } from 'utils/CommonFunction';
// ==============================|| EVENT TABLE ||============================== //

export default function SearchPublicNoticeTable({searchCriteria, applyGridOnReady,applySearch}) {

    const navigate = useNavigate()

    const [_searchCriteria, set_searchCriteria] = React.useState({searchCriteria});

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

    const columns = [
        {
            field: 'actions',
            headerName: 'Proof No.',
            width: 170,
            cellClassName: 'actions',
            renderCell: (params) => {
                return clickableLink('/proof/reply/' + params.row.id, params.row.refNo);
            },
        },
        {
            id: 'appId',
            field: 'appId',
            headerName: 'Application No./ Gazette Code/ Gazette Issue No.',
            width: 400,
            renderCell: (params) => {
                let appNo = params.row.appNo;
                let code = params.row.groupNo;
                let isssue = params.row.issueYear
                    + " Vol. " + FormatUtils.zeroPad(params.row.issueVolume, 3)
                    + ", No. " + FormatUtils.zeroPad(params.row.issueNo, 2)
                    + ", " + DateUtils.dateFormat(params.row.issueDate, "D MMM YYYY (ddd)");

                return <div style={{ margin: 4 }}>App No: {appNo}<br />Gazette Code: {code}<br />Issue: {isssue}</div>
            },
        },
        {
            id: 'actions',
            headerName: 'Status',
            flex: 1,
            minWidth: 150,
            renderCell: (params) => {
                return ProofStatus.getStatus_Eng(params);
            },
        },
        {
            id: 'created',
            field: 'created',
            headerName: 'Proof Issue Date',
            flex: 1,
            minWidth: 200,
            valueGetter: (params) => {
                return DateUtils.datetimeStr(params?.value);
            }
        },
        {
            id: 'replyDate',
            field: 'replyDate',
            headerName: 'Confirmed/ Return Date',
            flex: 1,
            minWidth: 200,
            type: 'dateTime',

            valueGetter: (params) => {
                const v = params?.value;
                if (v == null) return null;

                // 1) Number => epoch timestamp (ms or seconds)
                if (typeof v === "number") {
                    if (!Number.isFinite(v)) return null;

                    // Heuristic: if it's too small, it's probably seconds
                    // (ms in 2026 is ~1.7e12, seconds is ~1.7e9)
                    const ms = v < 1e11 ? v * 1000 : v;

                    const d = new Date(ms);
                    return Number.isNaN(d.getTime()) ? null : d;
                }

                // 2) Array => [Y, M, D, h, m, s]
                if (Array.isArray(v)) {
                    if (v.length < 3) return null;

                    const year = Number(v[0]);
                    const month = Number(v[1]); // expecting 1-12
                    const day = Number(v[2]);
                    const hour = Number(v[3] ?? 0);
                    const minute = Number(v[4] ?? 0);
                    const second = Number(v[5] ?? 0);

                    if (![year, month, day, hour, minute, second].every(Number.isFinite)) return null;
                    if (month < 1 || month > 12) return null;

                    const d = new Date(year, month - 1, day, hour, minute, second);

                    // Guard against JS "auto-fixing" invalid dates (e.g., Feb 31 -> Mar 2)
                    if (
                    d.getFullYear() !== year ||
                    d.getMonth() !== month - 1 ||
                    d.getDate() !== day
                    ) return null;

                    return d;
                }

                // 3) Optional: ISO string support (if it ever appears)
                if (typeof v === "string") {
                    const d = new Date(v);
                    return Number.isNaN(d.getTime()) ? null : d;
                }

                return null;
            },

            valueFormatter: (params) => {
                return params.value ? DateUtils.datetimeStr(params.value) : "";
            },
        },
        {
            id: 'contactPerson',
            field: 'contactPerson',
            headerName: 'Client',
            flex: 1,
            minWidth: 200,
            renderCell: (params) => {
                let company = params.row.enCompanyName != null?params.row.enCompanyName: params.row.chCompanyName;
                company = company != null ? company : "";
                if (company == "GLD"){
                    company = company + ": " + params.row.appCustName
                }
                return (<>
                    {params?.value}<br />{company}
                </>);
            }
        },
        {
            id: 'groupTitle',
            field: 'groupTitle',
            headerName: 'Gazette Group',
            flex: 1,
            minWidth: 200,
            valueGetter: (params) => {
                return (params?.value) ? (params?.value) : "";
            }
        },
        {
            id: 'fee',
            field: 'fee',
            headerName: 'Amount ($)',
            flex: 1,
            minWidth: 200,
            valueGetter: (params) => {
                return (params?.value) ? "$ " + FormatUtils.currencyFormat(params?.value) : "";
            }
        },
    ];

    function handleRowDoubleClick(params) {
        navigate('/proof/reply/' + params.row.id);
    }

    return (
        <div style={{ width: '100%' }}>
            <FiDataGrid
                columns={columns}
                customPageSize={10}
                getRowHeight={() => 'auto'}
                onRowDoubleClick={handleRowDoubleClick}
                applyGridOnReady={applyGridOnReady}
                applySearch = {applySearch}
                // doLoad={{
                //     url: LIST_PROOF,
                //     params: _searchCriteria,
                // }}
                doLoad={React.useMemo(() => ({
                    url: LIST_PROOF,
                    params: _searchCriteria,
                }), [_searchCriteria])}
            />
        </div>
    );
}
