import { Link } from '@inertiajs/react';
import { ArrowLeft, Loader2, Printer } from 'lucide-react';
import { Button } from '@/Components/ui/button';
import { StatusBadge } from '@/Components/Proto/UI/StatusBadge';
import { HistoryTimelinePopover } from '@/Components/MenuQuotations/QuotationDetailPage/HistoryTimelinePopover';
import { RebateInvoiceItemTable } from './RebateInvoiceItemTable';
import { useKomisiPenjualanPdf } from './useKomisiPenjualanPdf';
import { SCOPE_META } from './invoiceListConfig';

/**
 * Shared body for the eight legacy Generate Company Rebate detail screens. They differ only in
 * their record guard and their action buttons; the header block is byte-identical across all of
 * them in legacy (companyrebateinvoicedetail.php:12-20), so it lives here once.
 *
 * Every header field is display-only, as in legacy. Print is here because legacy renders
 * btn_print on all of them; the per-scope actions (Approve/Reject, Cancel, Change Status) come
 * in through the `footer` slot so a read-only scope simply passes nothing.
 */

const fmtRp = (n) => Number(n || 0).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });

const STATUS_TONES = {
    'Created': 'warning',
    'Approval Finance': 'primary',
    'Approval SM': 'primary',
    'Approval CEO': 'primary',
    'Billed': 'success',
    'Reject': 'danger',
    'Canceled': 'neutral',
    'Print': 'neutral',
};

/** One read-only field. Empty values render as an em dash so a blank never looks like a bug. */
// Same typography as `HeadVal` in MenuProjects/Projects/Detail — the app's established
// uppercase-label-above-value pair. The value carries the weight (font-medium) and the label
// stays the quieter of the two: before this the label was font-semibold against an unweighted
// value, so the caption read heavier than the fact it was captioning.
function Field({ label, children, className = '' }) {
    return (
        <div className={`min-w-0 ${className}`}>
            <p className="m-0 text-[10.5px] font-bold uppercase tracking-wide text-muted-foreground">{label}</p>
            <p className="m-0 mt-0.5 wrap-break-word text-[13px] font-medium text-foreground">{children || '—'}</p>
        </div>
    );
}

export function InvoiceDetailPage({ scope, invoice, items = [], itemsSource = 'database', itemsNotice = null, history = [], footer = null }) {
    const meta = SCOPE_META[scope] ?? { title: 'Generate Company Rebate', crumb: 'Detail' };
    const { print, printing } = useKomisiPenjualanPdf();

    // HistoryTimelinePopover's entry shape is PascalCase — {Status, Tanggal, User, Comment}.
    const timeline = history.map((h) => ({
        Status: h.status || '—',
        Tanggal: h.tanggal || '',
        User: h.nama || '',
        Comment: h.remark || '',
    }));

    return (
        <div className="space-y-4 px-6 py-5">
            <div className="flex flex-wrap items-start gap-3">
                <div className="min-w-0 flex-1">
                    <nav className="text-[11px] text-muted-foreground">
                        Company Rebate · Generate Company Rebate · {meta.crumb}
                    </nav>
                    <h1 className="mt-0.5 flex items-center gap-2 text-lg font-bold text-foreground">
                        View Details - Company Rebate
                        <span className="text-muted-foreground">#{invoice.id}</span>
                        {invoice.status ? (
                            <StatusBadge tone={STATUS_TONES[invoice.status] || 'neutral'}>{invoice.status}</StatusBadge>
                        ) : null}
                    </h1>
                </div>

                <div className="flex items-center gap-2">
                    {/* No `label`: the other 31 document-level history triggers in the app are the
                        bare clock icon. Passing a label shrinks the icon and stacks the word under
                        it, which made this one trigger a different shape and height from the
                        Print/Back buttons sitting right beside it. */}
                    <HistoryTimelinePopover entries={timeline} />
                    {/* Legacy renders Print on every detail screen (btn_print). */}
                    <Button variant="outline" className="h-9 px-4" onClick={() => print(invoice.id)} disabled={printing}>
                        {printing
                            ? <><Loader2 className="mr-2 size-4 animate-spin" />Preparing…</>
                            : <><Printer className="mr-2 size-4" />Print</>}
                    </Button>
                    <Button asChild variant="outline" className="h-9 px-4">
                        <Link href={route(`generate-company-rebates.${scope}`)}>
                            <ArrowLeft className="mr-2 size-4" />
                            Back
                        </Link>
                    </Button>
                </div>
            </div>

            <section className="rounded-xl border border-border bg-card">
                <header className="flex min-h-[46px] items-center border-b border-border px-5 py-1.5">
                    <h2 className="text-[13px] font-bold text-foreground">Invoice</h2>
                </header>
                <div className="grid grid-cols-2 gap-x-6 gap-y-4 p-5 md:grid-cols-4">
                    <Field label="ID">{invoice.id}</Field>
                    <Field label="No. Generate">{invoice.noGenerate || '—'}</Field>
                    <Field label="Tanggal">{invoice.tanggal}</Field>
                    <Field label="Creator">{invoice.creator}</Field>

                    <Field label="Company" className="md:col-span-2">{invoice.company}</Field>
                    <Field label="Division">{invoice.division}</Field>
                    <Field label="Industry">{invoice.industry}</Field>

                    <Field label="Sales Rebate ID">{invoice.salesRebateId}</Field>
                    <Field label="Rebate Creator">{invoice.rebateCreator}</Field>
                    <Field label="Rebate Sales">{invoice.rebateSales}</Field>
                    <Field label="Voucher">{invoice.isVoucher ? 'Yes' : 'No'}</Field>

                    <Field label="Validity (Invoice)">
                        {invoice.validityStart || invoice.validityEnd
                            ? `${invoice.validityStart || '—'} → ${invoice.validityEnd || '—'}`
                            : null}
                    </Field>
                    <Field label="Validity (Rebate)">
                        {invoice.rebateValidityStart || invoice.rebateValidityEnd
                            ? `${invoice.rebateValidityStart || '—'} → ${invoice.rebateValidityEnd || '—'}`
                            : null}
                    </Field>
                    <Field label="USD Rate">{fmtRp(invoice.usdRate)}</Field>
                    <Field label="Summary">{fmtRp(invoice.summary)}</Field>

                    <Field label="Pencairan" className="md:col-span-2">{invoice.pencairan}</Field>
                    <Field label="Comment Sales Creator" className="md:col-span-2">{invoice.commentSalesCreator}</Field>
                </div>
            </section>

            <section className="rounded-xl border border-border bg-card">
                <header className="flex min-h-[46px] items-center justify-between border-b border-border px-5 py-1.5">
                    <h2 className="text-[13px] font-bold text-foreground">List Details</h2>
                    <span className="text-[11px] font-semibold text-muted-foreground">
                        {items.length} {items.length === 1 ? 'line' : 'lines'}
                    </span>
                </header>
                <RebateInvoiceItemTable items={items} source={itemsSource} notice={itemsNotice} />
            </section>

            {/* Per-scope actions (decision pill, admin dialogs). Read-only scopes pass nothing. */}
            {footer}
        </div>
    );
}
