import { useMemo } from 'react';
import { formatIdr } from '@/lib/currencyFormat';
import { useResizableColumns, ColumnResizeGrip } from '@/lib/useResizableColumns';
import { DemoDataBadge } from '@/Components/NetSuite/DemoDataBadge';

const SECTION_CARD = 'flex flex-col overflow-visible rounded-xl border border-border bg-card shadow-sm';

// Resizable-column ids (left→right) + default widths for the table-fixed layout.
//
// The six aging buckets (NotYet / 30 / 60 / 90 / 120 / >120) used to be six SEPARATE columns.
// A row's balance only ever lands in ONE of them — which one is decided by `overdueDays`, the
// column right next to it — so five of the six were "Rp 0" on every row by construction.
// Measured on Credit Ceiling #21: the table came to 1860px inside a 1306px card, overflowing by
// 554px, and what got pushed off the right edge was Amount / Paid / Balance — the figures the
// credit decision is actually made on. Collapsed to one `aging` column carrying the bucket label
// plus its amount: 14 columns → 9, nothing lost (no per-bucket total is displayed anywhere).
const COLS = ['no', 'company', 'invoiceNo', 'dueDate', 'overdue', 'aging', 'amount', 'paid', 'balance'];
const COL_W = {
    no: 70, company: 220, invoiceNo: 130, dueDate: 120, overdue: 100,
    // aging was 200 to fit "label + amount"; the label alone ("Belum jatuh tempo" is the
    // longest) needs ~130. Measured on Credit Ceiling #17, that 70px cut the scroll container's
    // overflow from 44px to 6px — the table renders at 1204px in a 1204px box, and the 6px
    // residue is border-collapse rounding across nine columns, not clipped content (Balance
    // still prints in full). Before, the 44px hid the right edge of Amount/Paid/Balance.
    aging: 130, amount: 140, paid: 130, balance: 140,
};
const COL_W_FALLBACK = 150;

// The table is sized with minWidth, NOT width. An inline `width` beats the `w-full` class, so
// the table stayed pinned at the sum of COL_W (1250px) and left a 164px gutter inside its
// 1414px card on Review CS — reported 2026-08-20. With minWidth it fills the card when there
// is room and the wrapper's overflow-x-auto still scrolls it when there is not, which is what
// every other resizable table in this app does (LwrDenseTable, CreditCeilingTable, the
// Projects approval boards, …).

/**
 * Which bucket a row's balance sits in, and how much. Mirrors the six columns this replaced:
 * the server still sends all six fields, and exactly one of them is non-zero — so the bucket is
 * READ from the data rather than re-derived from overdueDays, and the two can never disagree.
 */
function agingBucket(r) {
    const buckets = [
        { label: 'Belum jatuh tempo', value: r.notYet, tone: 'text-muted-foreground' },
        { label: '1–30', value: r.balance30, tone: 'text-warning-text' },
        { label: '31–60', value: r.balance60, tone: 'text-stat-orange-text' },
        { label: '61–90', value: r.balance90, tone: 'text-danger-text' },
        { label: '91–120', value: r.balance120, tone: 'text-danger-text' },
        { label: '> 120', value: r.balanceThan120, tone: 'text-danger-text' },
    ];
    const hit = buckets.find((b) => Number(b.value || 0) !== 0);

    return hit ?? { label: '—', value: 0, tone: 'text-muted-foreground' };
}

function band(overdueDays) {
    if (overdueDays <= 0) return '';
    if (overdueDays <= 30) return 'bg-warning/15';
    if (overdueDays <= 60) return 'bg-stat-orange-text/15';
    return 'bg-danger/15';
}

/**
 * AR - Pending (bucket) — Approval SM / Process to Order. Bahasa desain baru
 * (kartu shadcn) untuk data kontrak customer-ar.pending.byCompany.
 * @param {{ data: object|null, loading: boolean }} props
 */
export function CustomerArPending({ data, loading }) {
    const rows = data?.rows ?? [];
    const summary = data?.summary ?? { creditLimit: 0, totalBalance: 0, overLimit: false };

    // Resizable columns — drag a header's right edge to resize.
    const { widthOf, startResize, resizingId } = useResizableColumns(COL_W, COL_W_FALLBACK);
    const tableWidth = useMemo(() => COLS.reduce((s, id) => s + widthOf(id), 0), [widthOf]);

    return (
        <section className={SECTION_CARD}>
            <header className="flex min-h-[66px] flex-wrap items-start justify-between gap-[18px] border-b border-border p-[18px_24px]">
                <div className="min-w-0 flex-1">
                    <p className="m-0 mb-[3px] text-[10px] font-extrabold uppercase tracking-[0.025em] text-muted-foreground">Customer Outstanding</p>
                    <h2 className="m-0 text-base font-bold leading-[1.3] tracking-[-0.005em] text-card-foreground">AR - Pending</h2>
                </div>
                <div className="ml-auto grid justify-items-end gap-1 text-right">
                    <span className="mb-[3px] text-[10px] font-extrabold uppercase tracking-[0.025em] text-muted-foreground">Credit Limit</span>
                    <strong className="text-lg font-extrabold tracking-[-0.01em] text-card-foreground">{formatIdr(summary.creditLimit)}</strong>
                </div>
            </header>
            <div className="flex-1 p-6">
                {/* issue #187 — never let a credit decision rest on fixture rows unlabelled. */}
                <DemoDataBadge show={Boolean(data?.isDemoData)} what="The credit limit and outstanding invoices below" />
                {summary.overLimit && (
                    <div className="mb-3 rounded-lg border border-danger bg-danger/10 px-4 py-2.5 text-[12px] font-semibold text-danger">
                        AR Company telah melebihi Credit Limit atau sudah Jatuh Tempo!
                    </div>
                )}
                <div className="overflow-x-auto rounded-xl border border-border">
                    <table style={{ minWidth: tableWidth }} className="w-full table-fixed border-collapse [&_tbody_td]:overflow-hidden [&_th]:whitespace-nowrap [&_th]:border-b [&_th]:border-border [&_th]:px-3 [&_th]:py-2.5 [&_th]:text-left [&_td]:whitespace-nowrap [&_td]:border-b [&_td]:border-border [&_td]:px-3 [&_td]:py-3 [&_td]:text-left [&_th]:bg-secondary/50 [&_th]:text-[11px] [&_th]:font-semibold [&_th]:uppercase [&_th]:tracking-wide [&_th]:text-muted-foreground [&_td]:text-[12px]">
                        <colgroup>
                            {COLS.map((id) => <col key={id} style={{ width: widthOf(id) }} />)}
                        </colgroup>
                        <thead>
                            <tr>
                                <th className="group/col relative">No<ColumnResizeGrip onMouseDown={(e) => startResize(e, 'no')} active={resizingId === 'no'} /></th>
                                <th className="group/col relative">Company<ColumnResizeGrip onMouseDown={(e) => startResize(e, 'company')} active={resizingId === 'company'} /></th>
                                <th className="group/col relative">Inv.No<ColumnResizeGrip onMouseDown={(e) => startResize(e, 'invoiceNo')} active={resizingId === 'invoiceNo'} /></th>
                                <th className="group/col relative">Due Date<ColumnResizeGrip onMouseDown={(e) => startResize(e, 'dueDate')} active={resizingId === 'dueDate'} /></th>
                                <th className="group/col relative !text-right">OverDue<ColumnResizeGrip onMouseDown={(e) => startResize(e, 'overdue')} active={resizingId === 'overdue'} /></th>
                                <th className="group/col relative">Aging<ColumnResizeGrip onMouseDown={(e) => startResize(e, 'aging')} active={resizingId === 'aging'} /></th>
                                <th className="group/col relative !text-right">Amount<ColumnResizeGrip onMouseDown={(e) => startResize(e, 'amount')} active={resizingId === 'amount'} /></th>
                                <th className="group/col relative !text-right">Paid<ColumnResizeGrip onMouseDown={(e) => startResize(e, 'paid')} active={resizingId === 'paid'} /></th>
                                <th className="group/col relative !text-right">Balance<ColumnResizeGrip onMouseDown={(e) => startResize(e, 'balance')} active={resizingId === 'balance'} /></th>
                            </tr>
                        </thead>
                        <tbody>
                            {loading && (
                                <tr><td colSpan={9} className="!whitespace-normal !px-3 !py-6 !text-center italic text-muted-foreground">Memuat AR…</td></tr>
                            )}
                            {!loading && rows.length === 0 && (
                                <tr><td colSpan={9} className="!whitespace-normal !px-3 !py-6 !text-center italic text-muted-foreground">Customer Have No A/R</td></tr>
                            )}
                            {!loading && rows.map((r) => (
                                <tr key={r.no} className={band(r.overdueDays)}>
                                    <td>{r.no}</td>
                                    <td>{r.company}</td>
                                    <td>{r.invoiceNo}</td>
                                    <td>{r.dueDate ?? '—'}</td>
                                    <td className="!text-right [font-variant-numeric:tabular-nums]">{r.overdueDays}</td>
                                    {/* Bucket LABEL only. The bucket's amount used to print here
                                        beside it, and it is the Balance column verbatim — a row's
                                        balance is what lands in a bucket, so the two can never
                                        differ. Measured on Credit Ceiling #17: all four rows had
                                        aging === balance, while row 4 (Amount 212.300.000, Paid
                                        40.000.000, Balance 172.300.000) showed the aging figure
                                        follows Balance and not Amount. Printing it twice wrapped
                                        the cell to two lines; row height is set by the cell
                                        padding and did NOT change (44px either way) — what the
                                        removal bought is the column width below. */}
                                    <td>
                                        {(() => {
                                            const b = agingBucket(r);
                                            return <span className={`text-[11px] font-bold ${b.tone}`}>{b.label}</span>;
                                        })()}
                                    </td>
                                    <td className="!text-right [font-variant-numeric:tabular-nums]">{formatIdr(r.amount)}</td>
                                    <td className="!text-right [font-variant-numeric:tabular-nums]">{formatIdr(r.paid)}</td>
                                    <td className="!text-right [font-variant-numeric:tabular-nums]">{formatIdr(r.balance)}</td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
                <div className="mt-4 flex items-center justify-between gap-4 rounded-2xl bg-secondary p-[16px_20px] border border-border">
                    <span className="text-[10px] font-extrabold uppercase tracking-[0.05em] text-muted-foreground">Total AR</span>
                    <strong className="whitespace-nowrap text-lg font-extrabold text-primary [font-variant-numeric:tabular-nums]">{formatIdr(summary.totalBalance)}</strong>
                </div>
            </div>
        </section>
    );
}
