import { AlertTriangle } from 'lucide-react';
import { Button } from '@/Components/ui/button';
import {
    Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle,
} from '@/Components/ui/dialog';
import { formatIdr } from '@/lib/currencyFormat';
import { agingInfo, arProblems } from './arProblems';

/**
 * Customer AR guard — Quotation Create.
 *
 * Fires on SUBMIT ONLY (user decision 2026-08-07). It used to also pop once per company as
 * soon as its AR loaded; that made it noise the user learned to dismiss, and the moment that
 * actually matters is the one just before the quotation is created.
 *
 * ⚠️ It runs BEFORE the request is sent, so it is not a replacement for `onError` — that still
 *    handles the 422 coming back, with its locked wording.
 *
 * ONE combined table: every outstanding invoice of every NetSuite customer mapped to this
 * company, in one list rather than grouped per customer. The credit decision being made here
 * is about the COMPANY, so splitting it would ask the approver to add the buckets up in their
 * head. (The panel behind the modal is the per-customer view; this is the roll-up.)
 *
 * Colour comes from the SHARED `agingInfo`, the same one the panel's legend uses — so "45 days
 * late" is the same orange in both places.
 */
export function CustomerArAlertModal({ open, data, onClose, onConfirm, processing = false }) {
    const { pastDue, pastDueTotal, totalAr, totalCreditLimit, excess, overLimit } = arProblems(data);
    const customers = data?.customers ?? [];
    // Customer stays a COLUMN, not a grouping — with several NetSuite codes on one company,
    // "whose invoice is this" is still the first question asked about a red row.
    const multiCustomer = customers.length > 1;
    const invoices = customers.flatMap((c) => (c.invoices ?? []).map((inv) => ({ ...inv, customer: c.customer })));
    // Worst first: the row that decides the conversation should not be page-two of the eye.
    const rows = [...invoices].sort((a, b) => (b.agingDays ?? 0) - (a.agingDays ?? 0));

    return (
        <Dialog open={open} onOpenChange={(next) => { if (!next) onClose(); }}>
            <DialogContent className="bg-card sm:max-w-3xl">
                <DialogHeader>
                    <DialogTitle className="flex items-center gap-2">
                        <span className="inline-grid size-7 shrink-0 place-items-center rounded-lg bg-danger-bg text-danger-text" aria-hidden="true">
                            <AlertTriangle className="size-4" strokeWidth={2.4} />
                        </span>
                        Customer Outstanding
                    </DialogTitle>
                    <DialogDescription>Periksa AR customer sebelum quotation ini dibuat.</DialogDescription>
                </DialogHeader>

                {/* Legacy wording, kept verbatim — the sentence approvers already know. */}
                <div className="rounded-lg border border-danger bg-danger/10 px-4 py-2.5 text-[12px] font-semibold text-danger-text">
                    AR Company telah melebihi Credit Limit atau sudah Jatuh Tempo!
                </div>

                <div className="flex flex-wrap items-center gap-x-5 gap-y-1.5 text-[12px]">
                    <span className="text-muted-foreground">Total AR <strong className="ml-1 font-extrabold tabular-nums text-card-foreground">{formatIdr(totalAr)}</strong></span>
                    <span className="text-muted-foreground">Credit Limit <strong className="ml-1 font-extrabold tabular-nums text-card-foreground">{formatIdr(totalCreditLimit)}</strong></span>
                    {overLimit && (
                        <span className="text-danger-text">Kelebihan <strong className="ml-1 font-extrabold tabular-nums">{formatIdr(excess)}</strong></span>
                    )}
                    {pastDue.length > 0 && (
                        <span className="text-danger-text">Jatuh tempo <strong className="ml-1 font-extrabold tabular-nums">{pastDue.length}</strong> · {formatIdr(pastDueTotal)}</span>
                    )}
                </div>

                {/* Same legend as the panel, so the row colours are readable without guessing. */}
                <div className="flex flex-wrap gap-3.5">
                    {[
                        { c: 'bg-warning', t: '1–30 hari' },
                        { c: 'bg-stat-orange-text', t: '31–60 hari' },
                        { c: 'bg-danger', t: '> 60 hari' },
                        { c: 'bg-primary-hover', t: 'Belum jatuh tempo' },
                    ].map((l) => (
                        <span key={l.t} className="inline-flex items-center gap-1.5 text-[11px] font-medium text-muted-foreground">
                            <i className={`inline-block size-[9px] rounded-full ${l.c}`} />{l.t}
                        </span>
                    ))}
                </div>

                <div className="max-h-[320px] overflow-y-auto rounded-lg border border-border">
                    {/* Detail-table treatment: white header, no grey band (locked ruling), body py-3. */}
                    <table className="w-full border-collapse [&_tbody_td]:border-b [&_tbody_td]:border-border/60 [&_tbody_td]:px-3.5 [&_tbody_td]:py-3 [&_tbody_td]:text-[12px] [&_tbody_tr:last-child_td]:border-b-0 [&_th]:whitespace-nowrap [&_th]:border-b [&_th]:border-border [&_th]:bg-card [&_th]:px-3.5 [&_th]:py-2.5 [&_th]:text-left [&_th]:text-[10px] [&_th]:font-extrabold [&_th]:uppercase [&_th]:tracking-[0.04em] [&_th]:text-muted-foreground">
                        <thead className="sticky top-0">
                            <tr>
                                {multiCustomer && <th>Customer</th>}
                                <th>No</th>
                                <th>Invoice Date</th>
                                <th>Due Date</th>
                                <th className="!text-right">Remaining</th>
                                <th className="!text-right">Aging</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            {rows.length === 0 && (
                                <tr><td colSpan={multiCustomer ? 7 : 6} className="!py-6 text-center italic text-muted-foreground">No outstanding invoices</td></tr>
                            )}
                            {rows.map((inv, i) => {
                                const ag = agingInfo(inv.agingDays);
                                const late = (inv.agingDays ?? 0) > 0;
                                return (
                                    <tr key={`${inv.customer}-${inv.no}-${i}`} className={ag.row}>
                                        {multiCustomer && <td className="text-muted-foreground">{inv.customer || '—'}</td>}
                                        <td className="font-semibold text-card-foreground">{inv.no}</td>
                                        <td className="text-muted-foreground">{inv.invoiceDate ?? '—'}</td>
                                        <td className={late ? 'font-medium text-danger-text' : 'text-muted-foreground'}>{inv.dueDate ?? '—'}</td>
                                        <td className="text-right font-medium tabular-nums text-card-foreground">{formatIdr(inv.remaining)}</td>
                                        <td className={`text-right tabular-nums ${late ? 'font-bold text-danger-text' : 'text-muted-foreground'}`}>
                                            {late ? `${Math.round(inv.agingDays)} hari` : '—'}
                                        </td>
                                        <td>
                                            <span className={`inline-flex items-center rounded-full px-2.5 py-1 text-[10px] font-bold ${ag.pill}`}>{ag.label}</span>
                                        </td>
                                    </tr>
                                );
                            })}
                        </tbody>
                    </table>
                </div>

                <DialogFooter>
                    {/* Destructive-dialog order (locked): Cancel FIRST — creating a quotation
                        against a breached credit limit must not be the easiest button to hit. */}
                    <Button type="button" variant="outline" disabled={processing} onClick={onClose}>Cancel</Button>
                    <Button type="button" variant="destructive" disabled={processing} onClick={onConfirm}>
                        {processing ? 'Menyimpan…' : 'Continue Create Quotation'}
                    </Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
}
