import { formatGrouped } from '@/lib/currencyFormat';
import { useCustomerAr } from '@/Hooks/useCustomerAr';

/**
 * CreditLimitNS — TOP / Credit Limit (NetSuite), wired to `customer-ar.list.byCompany`.
 *
 * Faithful port of the legacy `frameQuotationAR` iframe:
 *   plswaitnsquotationapprovalsm.php?companyID=…  →  getnsrestlistar2.php?NScustID=<NSCustomerID>
 *
 * Legacy loops the COMMA-SEPARATED company.NSCustomerID and, per code, calls
 * getar('entityid','is',<code>,'customer') — customsearch163 — then prints ONE table each:
 *
 *   header  altname · custentity_ps_paymentterm · creditlimit
 *   body    tranid · trandate · duedate · amountremaining, the ROW TINTED by aging days
 *   footer  "Subtotal AR" per customer, then one overall "TOTAL AR"
 *
 * TOTAL AR turns red when it exceeds the summed credit limit (getnsrestlistar2.php:138).
 * `CustomerArListService` already returns exactly this shape — including `overLimit`, which is
 * the same `totalAr > totalCreditLimit` test — so nothing new is computed here.
 *
 * ⚠️ `formulacurrency` is AGING DAYS, not currency, despite the name. Bands are legacy's
 *    (getnsrestlistar2.php:118-125): 1-30 yellow, 31-60 orange, >60 red. `<= 0` is not yet due
 *    and legacy leaves it untinted.
 *
 * FOUR DELIBERATE DEPARTURES from the legacy markup, all presentation-only — no figure changes.
 * The last two are 2026-08-24, after the panel was called too tall for the column it sits in:
 *  1. Column labels + a Status pill are added. Legacy encoded the aging band in the row colour
 *     ALONE, which the design system forbids (status must be text+colour, never colour alone).
 *  2. Money uses one format throughout. Legacy is internally inconsistent — US grouping for the
 *     credit limit and every invoice row (number_format($v,2,'.',',')), Indonesian for its two
 *     total cells (number_format($v,2,',','.')). The dominant US form is used for all of them.
 *  3. "Subtotal AR" is no longer a table footer row; it rides in the customer strip beside the
 *     credit limit it is judged against. And the overall "TOTAL AR" band renders only when there
 *     is MORE THAN ONE NS customer — with one, it printed the subtotal's digits a second time.
 *  4. Status is not its own column. Five columns needed a 520px table inside a 516px panel, so
 *     the aging pill lived permanently past the right edge; it now sits next to the due date it
 *     describes. The row tint is unchanged, and status is still text+colour, never colour alone.
 *
 * Legacy's two empty states mean OPPOSITE things and are kept apart, wording verbatim:
 *   no NS code at all   → "Customer Have No Synchronization To Oracle"  (a missing link)
 *   NS code but no rows → "Customer Have No A/R"                        (good news)
 */

const AGING_BANDS = [
    { max: 0, label: 'Future', row: '', pill: 'bg-primary/10 text-primary' },
    { max: 30, label: '1-30', row: 'bg-warning/10', pill: 'bg-warning/15 text-warning-text' },
    { max: 60, label: '31-60', row: 'bg-stat-orange-text/10', pill: 'bg-stat-orange-text/15 text-stat-orange-text' },
    { max: Infinity, label: '> 60', row: 'bg-danger/10', pill: 'bg-danger/15 text-danger-text' },
];

function agingBand(days) {
    const d = days === null || days === undefined ? 0 : Number(days);
    return AGING_BANDS.find((b) => d <= b.max) ?? AGING_BANDS[0];
}

const TH = 'whitespace-nowrap border-b border-border px-3 py-2 text-left text-[10px] font-bold uppercase tracking-wider text-muted-foreground';
const TD = 'whitespace-nowrap border-b border-border/60 px-3 py-3 text-[12px] text-foreground';

export function CreditLimitNS({ companyId = null, nsCustomerId = '' }) {
    const { data, loading } = useCustomerAr(companyId, 'customer-ar.list.byCompany');

    const customers = data?.customers ?? [];
    const overLimit = data?.overLimit ?? false;
    // Legacy keys "not synchronised" off the NSCustomerID column being blank, before any call.
    const synced = String(nsCustomerId ?? '').trim() !== '';
    // One NS customer → the customer strip already IS the grand total.
    const single = customers.length === 1;

    return (
        <div className="rounded-xl border border-border p-4">
            <div className="mb-3 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1.5">
                <h3 className="m-0 text-[13px] font-bold text-card-foreground">TOP / Credit Limit (NS)</h3>
                <span className="truncate text-[11px] text-muted-foreground">· NetSuite{nsCustomerId ? ` · ${nsCustomerId}` : ''}</span>
            </div>

            {/* NO demo-data badge here — user decision 2026-08-24, taken after being told what
                issue #187 (2026-07-31) had decided: that fixture figures on a credit screen must
                carry a label. It was removed anyway, for length. Nothing server-side changed —
                `data.isDemoData` still arrives on every response — so restoring it is one line:
                <DemoDataBadge show={Boolean(data?.isDemoData)} what="The credit limit and
                outstanding invoices below" />. Four other screens still render it. */}

            {!synced ? (
                <Notice>Customer Have No Synchronization To Oracle</Notice>
            ) : loading ? (
                <Notice>Memuat AR…</Notice>
            ) : customers.length === 0 ? (
                <Notice>Customer Have No A/R</Notice>
            ) : (
                <div className="flex flex-col gap-3">
                    {customers.map((c) => (
                        <div key={c.nsCode} className="overflow-hidden rounded-lg border border-border">
                            {/* Legacy's thead (customer · term · limit) AND its "Subtotal AR" footer
                                row, merged into one strip. They were 100px of card apart while saying
                                one thing — and with a single NS customer the subtotal repeated the
                                TOTAL AR band verbatim (reported 2026-08-24: the same 198,981,008.70
                                printed twice). Same figures, same order, one band. */}
                            <div className="flex flex-wrap items-start justify-between gap-x-4 gap-y-1.5 border-b border-border bg-secondary/40 px-3 py-2">
                                {/* WHO on the left, HOW MUCH on the right (user 2026-08-24). The
                                    payment term sits under the customer it belongs to rather than
                                    across the row from it, so the two money figures get the whole
                                    right-hand side and stay on one line. */}
                                <div className="min-w-0">
                                    <span className="block truncate text-[12px] font-bold text-card-foreground">{c.customer || '—'}</span>
                                    <span className="block text-[11px] text-muted-foreground">{c.paymentTerm || '—'}</span>
                                </div>
                                <div className="flex flex-wrap items-baseline justify-end gap-x-4 gap-y-0.5 text-right">
                                    <span className="text-[11px] text-muted-foreground">
                                        Limit <span className="font-semibold tabular-nums text-card-foreground">{formatGrouped(c.creditLimit, { decimals: 2 })}</span>
                                    </span>
                                    <span className="text-[11px] text-muted-foreground">
                                        AR <span className="font-bold tabular-nums text-card-foreground">{formatGrouped(c.subtotal, { decimals: 2 })}</span>
                                    </span>
                                    {/* With ONE customer the global over-limit test IS this customer's,
                                        so the flag belongs here; with several it belongs on the Total
                                        band below, which is what it actually compares. */}
                                    {single && overLimit && (
                                        <span className="rounded-full bg-danger px-2 py-0.5 text-[10px] font-bold text-white">Over Limit</span>
                                    )}
                                </div>
                            </div>

                            <div className="overflow-x-auto">
                                <table className="w-full min-w-[380px] border-collapse">
                                    <thead>
                                        <tr>
                                            <th className={TH}>Invoice No</th>
                                            <th className={TH}>Invoice Date</th>
                                            <th className={TH}>Due Date</th>
                                            <th className={`${TH} text-right`}>Amount (IDR)</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {c.invoices.length === 0 && (
                                            <tr><td className={`${TD} !whitespace-normal text-center italic text-muted-foreground`} colSpan={4}>Customer Have No A/R</td></tr>
                                        )}
                                        {c.invoices.map((inv, i) => {
                                            const band = agingBand(inv.agingDays);
                                            return (
                                                <tr key={`${inv.no}-${i}`} className={band.row}>
                                                    <td className={`${TD} font-semibold`}>{inv.no || '—'}</td>
                                                    <td className={`${TD} tabular-nums text-muted-foreground`}>{inv.invoiceDate || '—'}</td>
                                                    {/* The aging pill rides WITH the due date instead of
                                                        owning a fifth column. Five columns needed 520px in
                                                        a 516px panel, so Status sat permanently off-screen
                                                        behind a scrollbar — the tint was doing the job
                                                        alone, which the design system forbids. */}
                                                    <td className={TD}>
                                                        <span className="inline-flex items-center gap-1.5">
                                                            <span className="tabular-nums text-muted-foreground">{inv.dueDate || '—'}</span>
                                                            <span className={`inline-flex items-center rounded-full px-1.5 py-0.5 text-[10px] font-bold ${band.pill}`}>{band.label}</span>
                                                        </span>
                                                    </td>
                                                    <td className={`${TD} text-right font-medium tabular-nums`}>{formatGrouped(inv.remaining, { decimals: 2 })}</td>
                                                </tr>
                                            );
                                        })}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    ))}

                    {/* Legacy "TOTAL AR" — only meaningful once there is more than one NS customer
                        to total. With one, it restated the strip above it. */}
                    {!single && (
                        <div className={`flex flex-wrap items-center justify-between gap-3 rounded-lg border px-4 py-3 ${overLimit ? 'border-danger/40 bg-danger text-white' : 'border-border bg-secondary'}`}>
                            <span className="inline-flex items-center gap-2 text-[11px] font-bold uppercase tracking-wider opacity-90">
                                Total AR
                                {overLimit && <span className="rounded-full bg-white/20 px-2 py-0.5 text-[10px] font-bold normal-case tracking-normal">Over Limit</span>}
                            </span>
                            <span className="text-[13px] font-bold tabular-nums">{formatGrouped(data?.totalAr, { decimals: 2 })}</span>
                        </div>
                    )}
                </div>
            )}
        </div>
    );
}

/** Legacy printed these as a bare <p><strong>…</strong></p>; same words, framed. */
function Notice({ children }) {
    return (
        <div className="flex h-20 items-center justify-center rounded-lg border border-dashed border-border bg-muted/20 px-4 text-center">
            <span className="text-xs font-semibold text-muted-foreground">{children}</span>
        </div>
    );
}
