import { useState } from 'react';
import { Link, useForm } from '@inertiajs/react';
import { ArrowLeft, Pencil } from 'lucide-react';
import AppLayout from '@/Layouts/AppLayout';
import { cn } from '@/lib/utils';
import { Button } from '@/Components/ui/button';
import { StatusBadge } from '@/Components/Proto/UI/StatusBadge';
import { QuotationHistoryCell } from '@/Components/MenuQuotations/QuotationDetailPage/QuotationHistoryCell';
import { QuotationAuditCell } from '@/Components/MenuQuotations/QuotationDetailPage/QuotationAuditCell';
import { HistoryTimelinePopover } from '@/Components/MenuQuotations/QuotationDetailPage/HistoryTimelinePopover';
import { PrintActionButtons } from '@/Components/MenuQuotations/QuotationDetailPage/PrintActionButtons';
import { useToast } from '@/Components/Toast';
import { DecisionBar } from '@/Components/MenuSampleOrders/DecisionBar';
import { DecisionConfirmDialog } from '@/Components/MenuSampleOrders/DecisionConfirmDialog';
import { dpBasis, dpRecalc } from '@/lib/quotation/dpCalc';


// Maps real quotationstatus.StatusName / quotationdetailstatus.StatusDetailName to a tone.
const STATUS_TONES = {
    'Request': 'warning',
    'Approval SM': 'primary',
    'Approval PM': 'primary',
    'Revise': 'warning',
    'Reject': 'danger',
    'Cancel': 'danger',
    'Print': 'success',
    'Feedback': 'primary',
    'Process To Order': 'success',
    'Good Shipped': 'success',
    'Good Receive': 'success',
    'Update PO Number': 'neutral',
    'Update Delivery Fee': 'neutral',
    'Price Indication': 'neutral',
};
function statusTone(status) {
    return STATUS_TONES[status] || 'neutral';
}

const DOC_SECTION = 'relative rounded-xl border border-border bg-card px-4 pt-3.5 pb-3 shadow-sm';
const DOC_HEADING = 'm-0 mb-3 flex items-center gap-2 text-xs font-bold uppercase tracking-wide text-foreground';
const DOC_ICON = 'inline-grid size-6 shrink-0 place-items-center rounded-full border border-primary/50 bg-transparent text-primary';
const BACK_BTN = 'inline-flex h-9 items-center justify-center gap-1.5 rounded-lg border border-input bg-card px-4 text-center text-xs font-bold text-foreground transition-colors hover:border-primary hover:text-primary';
// Compact input for inline editing inside a DocList row.
const INLINE_INPUT = 'h-7 w-full rounded-md border border-input bg-card px-2 text-xs font-medium text-foreground outline-none transition-colors focus:border-primary focus:ring-1 focus:ring-primary';

// `edits` maps a field label → an inline editable control. Such fields render the
// control in place (no separate edit panel) and flag the label with a pencil + bold
// so it's obvious to the user that the value is editable right there.
function DocList({ fields, edits }) {
    if (!fields || Object.keys(fields).length === 0)
        return <p className="px-0 py-1 text-[0.82rem] text-muted-foreground">Tidak ada data.</p>;
    return (
        <dl className="grid gap-0">
            {Object.entries(fields).map(([key, val]) => {
                const edit = edits?.[key];
                return (
                    <div key={key} className={cn('grid grid-cols-[minmax(0,110px)_1fr] gap-2.5 border-b border-border/40 py-1.75 last:border-b-0', edit ? 'items-center' : 'items-baseline')}>
                        <dt className={cn('m-0 flex items-center gap-1 text-[11px]', edit ? 'font-semibold text-foreground' : 'font-medium text-muted-foreground')}>
                            {key}
                            {edit && <Pencil className="size-3 shrink-0 text-primary" aria-hidden="true" />}
                        </dt>
                        <dd className="m-0 wrap-break-word text-xs font-medium text-foreground">{edit ?? (val || '—')}</dd>
                    </div>
                );
            })}
        </dl>
    );
}

function getCreatedOnString(q) {
    let dateStr = '';
    if (q.history?.entries && q.history.entries.length > 0) {
        const oldest = q.history.entries[q.history.entries.length - 1];
        if (oldest?.Tanggal && oldest.Tanggal !== '—') {
            dateStr = oldest.Tanggal;
        }
    }
    if (!dateStr) {
        dateStr = q.general?.['Quotation Date'] || q.general?.['Sample Order Date'] || q.tanggal || '';
    }
    if (!dateStr || dateStr === '—') return '';
    try {
        const parts = dateStr.trim().split(/\s+/);
        const datePart = parts[0];
        const timePart = parts[1] || '';
        
        let formattedDate = datePart;
        if (datePart.includes('-')) {
            const [y, m, d] = datePart.split('-');
            const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
            const monthName = months[parseInt(m, 10) - 1] || m;
            formattedDate = `${parseInt(d, 10)} ${monthName} ${y}`;
        }
        
        let formattedTime = '';
        if (timePart) {
            const tParts = timePart.split(':');
            if (tParts.length >= 2) {
                formattedTime = `${tParts[0]}:${tParts[1]}`;
            }
        }
        
        if (formattedDate && formattedTime) {
            return `Created on ${formattedDate} · ${formattedTime}`;
        } else if (formattedDate) {
            return `Created on ${formattedDate}`;
        }
    } catch (e) {
        // Ignore
    }
    return `Created on ${dateStr}`;
}

export default function QuotationGoodReceiveDetail({ quotation, printActions = null }) {
    const { show: showToast } = useToast();
    const q = quotation;
    const editable = q.editable || {};

    // Action posts carry no payload; useForm supplies `processing`.
    const actionForm = useForm({});

    // Legacy renders the Good Receive button only while the quotation is still
    // on Process To Order (11) — the server enforces the same rule.
    const canReceive = q.statusId === 11;

    // `printActions` arrives from the server as per-document verdicts. Note this page's
    // Quotation gate is WIDER than Process to Order's — legacy lets status 10/11 print from
    // Good Receive (quotationgoodreceive.php:1284) but not from PTO. That difference cannot
    // be expressed by a flag derived in the browser, which is why it moved server-side.

    // `.transform()` returns undefined in @inertiajs/react 3.0 — it only assigns transformRef
    // — so chaining `.transform(...).post(...)` throws before a request is ever made and the
    // button does nothing. Every other caller in this app states the two separately.
    const runAct = (routeName, comment) => {
        actionForm.transform(() => ({ comment }));
        actionForm.post(route(routeName, q.id), {
            onError: () => showToast('Please check the form and try again.', 'error'),
        });
    };

    // Legacy btn-updateDFee form — PascalCase keys match the validation rules.
    const updateForm = useForm({
        CustomerPONo: editable.customerPONo || '',
        PODate: editable.poDate || '',
        DeliveryFee: editable.deliveryFee ? String(editable.deliveryFee) : '',
        DPPercentage: editable.dpPercentage ? String(editable.dpPercentage) : '',
        DPPriceUSD: editable.dpPriceUsd ? String(editable.dpPriceUsd) : '',
        DPPriceIDR: editable.dpPriceIdr ? String(editable.dpPriceIdr) : '',
    });

    const runUpdate = () => {
        updateForm.post(route('quotations.good-receive.update', q.id), {
            onError: () => showToast('Please check the form and try again.', 'error'), preserveScroll: true });
    };

    // ── Decision flow ────────────────────────────────────────────────────────────
    // `window.confirm()` is banned here (ui-conventions.md "Decision bar", notifications.md
    // ⛔ #3): it is OS chrome that cannot be styled, carries none of the record it is about,
    // and looks nothing like the confirm every other approval screen shows. Good Receive
    // logs to quotationassignment.Comment, so it opens the dialog WITH the comment box;
    // only the plain "Update Quotation?" save runs comment-less.
    const [pending, setPending] = useState(null);
    const [comment, setComment] = useState('');
    // `withComment` marks the decisions that log to quotationassignment.Comment. The plain
    // "Update Quotation?" save has no such column, so it stays a bare confirm rather than
    // offering a box whose text would go nowhere.
    const ask = (tone, label, run, withComment = false) => {
        if (actionForm.processing || updateForm.processing) return;
        setComment('');
        setPending({ tone, label, run, withComment });
    };
    const confirmPending = () => { const p = pending; setPending(null); p?.run(comment.trim()); };

    // Legacy DPCalc: three-way sync between DP %, DP USD and DP IDR via the VAT-inclusive
    // totals — editing one recomputes the other two. Shared with Process to Order and the
    // shared detail page (lib/quotation/dpCalc) so the three cannot drift apart.
    const basis = dpBasis(editable);

    const onDpChange = (field, raw) => {
        const next = dpRecalc(field, raw, basis);
        // null = not a number yet; store the keystroke without blanking the other two.
        if (next === null) {
            updateForm.setData(field, raw);

            return;
        }
        updateForm.setData((d) => ({ ...d, ...next }));
    };

    // Build section fields — fallback ke top-level fields kalau detail belum ada
    const generalFields = q.general || {
        'No': q.id,
        'Quotation Status': q.statusLabel || '—',
        'Feedback Status': q.feedback || '—',
        'Quotation Date': q.tanggal || '—',
        'Creator': q.creator || '—',
        'Sales': q.sales || '—',
    };

    const companyFields = q.companyContact || {
        'Company Name': q.company || '—',
        'Division': q.division || '—',
        'Industry': q.industry || '—',
        'Company Category': q.companyCategory || '—',
    };

    const orderFields = q.order || {
        'Customer PO No': q.poNo || '—',
        'Customer PO Date': q.poDate || '—',
        'Delivery Date': q.deliveryDate || '—',
    };

    const pricingFields   = q.pricing    || {};
    const termsFields     = q.terms      || {};
    const businessFields  = q.business   || { 'Division': q.division || '—', 'Industry': q.industry || '—', 'Company Category': q.companyCategory || '—' };
    const additionalFields = q.additional || { 'Creator': q.creator || '—', 'Sales': q.sales || '—', 'Comment': q.comment || '—' };
    const historyFields   = q.history?.fields || {};
    const lineItems       = q.lineItems  || [];
    const totals          = q.totals     || { usd: '$0', idr: 'Rp 0', dpPct: '0.00%', dpUsd: '$0', deliveryFee: '$0' };

    // Inline editable controls keyed by the section field label. The Order and Pricing
    // sections render these in place (no separate "Order & Payment" edit panel).
    const editErr = (msg) => msg ? <span className="mt-0.5 block text-[10px] font-medium text-danger">{msg}</span> : null;
    const orderEdits = {
        'Customer PO No': (
            <>
                <input type="text" value={updateForm.data.CustomerPONo} onChange={(e) => updateForm.setData('CustomerPONo', e.target.value)} placeholder="Insert PO No" className={INLINE_INPUT} />
                {editErr(updateForm.errors.CustomerPONo)}
            </>
        ),
        'Customer PO Date': (
            <>
                <input type="date" value={updateForm.data.PODate} onChange={(e) => updateForm.setData('PODate', e.target.value)} className={INLINE_INPUT} />
                {editErr(updateForm.errors.PODate)}
            </>
        ),
    };
    const pricingEdits = {
        'Delivery Fee': (
            <>
                <input type="text" inputMode="decimal" value={updateForm.data.DeliveryFee} onChange={(e) => updateForm.setData('DeliveryFee', e.target.value)} placeholder="Ex: 15100.99" className={INLINE_INPUT} />
                {editErr(updateForm.errors.DeliveryFee)}
            </>
        ),
        'DP Percentage': (
            <>
                <input type="text" inputMode="decimal" value={updateForm.data.DPPercentage} onChange={(e) => onDpChange('DPPercentage', e.target.value)} className={INLINE_INPUT} />
                {editErr(updateForm.errors.DPPercentage)}
            </>
        ),
        'DP Price (USD)': (
            <>
                <input type="text" inputMode="decimal" value={updateForm.data.DPPriceUSD} onChange={(e) => onDpChange('DPPriceUSD', e.target.value)} className={INLINE_INPUT} />
                {editErr(updateForm.errors.DPPriceUSD)}
            </>
        ),
        'DP Price (IDR)': (
            <>
                <input type="text" inputMode="decimal" value={updateForm.data.DPPriceIDR} onChange={(e) => onDpChange('DPPriceIDR', e.target.value)} className={INLINE_INPUT} />
                {editErr(updateForm.errors.DPPriceIDR)}
            </>
        ),
    };

    return (
        <section className="flex min-w-0 flex-col gap-4.5">
            <header className="flex items-center justify-between gap-4">
                <div>
                    <p className="mb-1.5 flex items-center gap-2 text-xs font-semibold text-muted-foreground">
                        <Link href={route('quotations.good-receive')} className="text-muted-foreground no-underline hover:text-primary">Good Receive</Link>
                        <span aria-hidden="true">›</span>
                        <span className="text-foreground">View Quotation</span>
                    </p>
                </div>
                <Link href={route('quotations.good-receive')} className={BACK_BTN}>
                    <ArrowLeft className="size-3.5" />
                    Back to List
                </Link>
            </header>

            {/* Hero */}
            <div className="flex items-center justify-between gap-4 mt-1">
                <div className="flex flex-col gap-1 min-w-0">
                    <div className="flex items-center gap-3">
                        <h1 className="m-0 text-2xl font-extrabold tracking-tight text-foreground">Quotation #{q.id}</h1>
                        {q.statusLabel && (
                            <StatusBadge tone={statusTone(q.status)}>{q.statusLabel}</StatusBadge>
                        )}
                    </div>
                    {getCreatedOnString(q) && (
                        <p className="m-0 text-[13px] font-medium text-muted-foreground">{getCreatedOnString(q)}</p>
                    )}
                </div>
            </div>


            {/* Stats Strip */}
            <article className="flex items-center gap-2 rounded-2xl border border-border bg-card shadow-sm p-[14px_18px]">
                <div className="grid min-w-0 flex-1 grid-cols-5 max-[860px]:grid-cols-2 gap-0">
                    <div className="flex min-w-0 items-center gap-2.5 p-[0_14px]">
                        <div><small className="mb-px block text-[10px] font-medium text-muted-foreground">Subtotal (USD)</small><strong className="block whitespace-nowrap text-base font-extrabold leading-[1.1] text-card-foreground">{totals.usd}</strong></div>
                    </div>
                    <div className="flex min-w-0 items-center gap-2.5 border-l border-border p-[0_14px]">
                        <div><small className="mb-px block text-[10px] font-medium text-muted-foreground">Subtotal (IDR)</small><strong className="block whitespace-nowrap text-base font-extrabold leading-[1.1] text-card-foreground">{totals.idr}</strong></div>
                    </div>
                    <div className="flex min-w-0 items-center gap-2.5 border-l border-border p-[0_14px]">
                        <div><small className="mb-px block text-[10px] font-medium text-muted-foreground">DP Percentage</small><strong className="block whitespace-nowrap text-base font-extrabold leading-[1.1] text-card-foreground">{totals.dpPct}</strong></div>
                    </div>
                    <div className="flex min-w-0 items-center gap-2.5 border-l border-border p-[0_14px]">
                        <div><small className="mb-px block text-[10px] font-medium text-muted-foreground">DP Price (USD)</small><strong className="block whitespace-nowrap text-base font-extrabold leading-[1.1] text-card-foreground">{totals.dpUsd}</strong></div>
                    </div>
                    <div className="flex min-w-0 items-center gap-2.5 border-l border-border p-[0_14px]">
                        <div><small className="mb-px block text-[10px] font-medium text-muted-foreground">Delivery Fee</small><strong className="block whitespace-nowrap text-base font-extrabold leading-[1.1] text-card-foreground">{totals.deliveryFee}</strong></div>
                    </div>
                </div>
                {q.history?.entries?.length > 0 && (
                    <div className="shrink-0 self-center border-l border-border pl-3">
                        <HistoryTimelinePopover entries={q.history.entries} />
                    </div>
                )}
            </article>

            {/* Doc Sections */}
            <div className="grid grid-cols-3 gap-3.5 max-[1180px]:grid-cols-2 max-[860px]:grid-cols-1">
                <section className={DOC_SECTION} data-section-id="general">
                    <h3 className={DOC_HEADING}>
                        <span className={DOC_ICON} aria-hidden="true">
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                <circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/>
                            </svg>
                        </span>
                        General Information
                    </h3>
                    <DocList fields={generalFields} />
                </section>

                <section className={DOC_SECTION} data-section-id="company">
                    <h3 className={DOC_HEADING}>
                        <span className={DOC_ICON} aria-hidden="true">
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>
                            </svg>
                        </span>
                        Company &amp; Contact
                    </h3>
                    <DocList fields={companyFields} />
                </section>

                <section className={DOC_SECTION} data-section-id="order">
                    <h3 className={DOC_HEADING}>
                        <span className={DOC_ICON} aria-hidden="true">
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                <rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/>
                            </svg>
                        </span>
                        Order Information
                    </h3>
                    <DocList fields={orderFields} edits={orderEdits} />
                </section>

                <section className={DOC_SECTION} data-section-id="pricing">
                    <h3 className={DOC_HEADING}>
                        <span className={DOC_ICON} aria-hidden="true">
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                <line x1="12" y1="2" x2="12" y2="22"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/>
                            </svg>
                        </span>
                        Pricing Information
                    </h3>
                    <DocList fields={pricingFields} edits={pricingEdits} />
                </section>

                <section className={DOC_SECTION} data-section-id="terms">
                    <h3 className={DOC_HEADING}>
                        <span className={DOC_ICON} aria-hidden="true">
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
                                <polyline points="14 2 14 8 20 8"/><polyline points="9 14 11 16 15 12"/>
                            </svg>
                        </span>
                        Terms &amp; Conditions
                    </h3>
                    <DocList fields={termsFields} />
                </section>

                <section className={DOC_SECTION} data-section-id="business">
                    <h3 className={DOC_HEADING}>
                        <span className={DOC_ICON} aria-hidden="true">
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                <path d="M3 21h18"/><path d="M5 21V7l7-4 7 4v14"/>
                                <path d="M10 9h.01"/><path d="M14 9h.01"/><path d="M10 13h.01"/><path d="M14 13h.01"/><path d="M10 17h.01"/><path d="M14 17h.01"/>
                            </svg>
                        </span>
                        Business Information
                    </h3>
                    <DocList fields={businessFields} />
                    <h4 className="mt-4 mb-2 border-t border-dashed border-border pt-3 text-[11px] font-extrabold uppercase tracking-wide text-muted-foreground">Additional Information</h4>
                    <DocList fields={additionalFields} />
                </section>
            </div>

            {/* Line Items */}
            <article className="rounded-2xl border border-border bg-card shadow-sm">
                <header className="flex items-center justify-between gap-3 border-b border-border p-[18px_22px]">
                    <div className="flex items-center gap-2.5">
                        <span className={DOC_ICON} aria-hidden="true">
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                <line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/>
                                <circle cx="4" cy="6" r="1"/><circle cx="4" cy="12" r="1"/><circle cx="4" cy="18" r="1"/>
                            </svg>
                        </span>
                        <div className="[&>h2]:m-0 [&>h2]:text-sm [&>h2]:font-extrabold [&>h2]:leading-[1.2] [&>h2]:text-card-foreground [&>small]:block [&>small]:text-[11px] [&>small]:font-medium [&>small]:text-muted-foreground">
                            <h2>Quotation Details</h2>
                            <small>Line items breakdown</small>
                        </div>
                    </div>
                </header>

                {lineItems.length === 0 ? (
                    <p className="p-6 text-[0.85rem] text-muted-foreground">Tidak ada line item.</p>
                ) : (
                    <div className="overflow-x-auto rounded-xl border border-border">
                        <table className="w-full min-w-575 border-collapse [&_thead_th]:whitespace-nowrap [&_thead_th]:border-b [&_thead_th]:border-border [&_thead_th]:px-3 [&_thead_th]:py-3 [&_thead_th]:text-left [&_thead_th]:text-[11px] [&_thead_th]:font-semibold [&_thead_th]:uppercase [&_thead_th]:tracking-wide [&_thead_th]:text-muted-foreground [&_th.number]:text-right [&_td.number]:text-right [&_th.text-center]:text-center [&_td.text-center]:text-center [&_tbody_td]:whitespace-nowrap [&_tbody_td]:border-b [&_tbody_td]:border-border/50 [&_tbody_td]:px-3 [&_tbody_td]:py-3 [&_tbody_td]:text-[11px] [&_tbody_td]:font-medium [&_tbody_td]:text-foreground [&_tbody_tr:last-child_td]:border-b-0 [&_tbody_tr:hover]:bg-secondary/60">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Status</th>
                                    <th>Principal</th>
                                    <th>Product Name</th>
                                    <th className="number">Qty</th>
                                    <th>Pack ID</th>
                                    <th>Satuan</th>
                                    <th className="number">Order Qty</th>
                                    <th>Satuan Order</th>
                                    <th className="number">USD Rate</th>
                                    <th className="number">Unit USD</th>
                                    <th className="number">Total USD</th>
                                    <th className="number">Unit IDR</th>
                                    <th className="number">Total IDR</th>
                                    <th>Application</th>
                                    <th>Remarks</th>
                                    <th>Remark Internal</th>
                                    <th className="!text-center">Quotation History</th>
                                    <th className="!text-center">History</th>
                                </tr>
                            </thead>
                            <tbody>
                                {lineItems.map(item => (
                                    <tr key={item.id}>
                                        <td className="tabular-nums">{item.id}</td>
                                        <td>
                                            {item.statusLabel
                                                ? <StatusBadge tone={statusTone(item.status)}>{item.statusLabel}</StatusBadge>
                                                : '—'}
                                        </td>
                                        <td>{item.principalName || '—'}</td>
                                        <td><strong className="font-semibold text-foreground">{item.productName || '—'}</strong></td>
                                        <td className="number">{item.qty || '—'}</td>
                                        <td>{item.quotationPackId || '—'}</td>
                                        <td>{item.satuanId || '—'}</td>
                                        <td className="number">{item.orderQty || '—'}</td>
                                        <td>{item.satuanOrderQty || '—'}</td>
                                        <td className="number">{item.usdRate || '—'}</td>
                                        <td className="number">{item.unitUsd || '—'}</td>
                                        <td className="number"><strong>{item.totalUsd ? '$' + item.totalUsd : '—'}</strong></td>
                                        <td className="number">{item.unitIdr || '—'}</td>
                                        <td className="number">{item.totalIdr ? 'Rp ' + item.totalIdr : '—'}</td>
                                        <td>{item.application || '—'}</td>
                                        <td>{item.remarks || '—'}</td>
                                        <td>{item.remarkInternal || '—'}</td>
                                        {/* Legacy listquotationdetailsview.php "QuotationHistory": last 10 quoted
                                            lines of this product for the company, across all its quotations. */}
                                        <td className="text-center">
                                            <QuotationHistoryCell items={item.quotationHistory} />
                                        </td>
                                        {/* Legacy "History": this line's quotationdetailsassignment audit log. */}
                                        <td className="text-center">
                                            <QuotationAuditCell items={item.history} />
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}
            </article>

            {/* Print / Download — UI-only (legacy "Action" row); backend wiring is a follow-up. */}
            {/* Print Performa Inv. (Pelunasan) saves the order fields as a side effect — legacy
                reads them from THIS form's inputs, not from the stored row. */}
            <PrintActionButtons printActions={printActions}
                getPelunasanPayload={() => ({
                    CustomerPONo: updateForm.data.CustomerPONo || '',
                    PODate: updateForm.data.PODate || null,
                    DeliveryFee: Number(updateForm.data.DeliveryFee) || 0,
                    DPPercentage: Number(updateForm.data.DPPercentage) || 0,
                    DPPriceUSD: Number(updateForm.data.DPPriceUSD) || 0,
                    DPPriceIDR: Number(updateForm.data.DPPriceIDR) || 0,
                })}
                leadingAction={
                <Button type="button" disabled={updateForm.processing} onClick={() => ask('approve', 'Update Quotation?', runUpdate)}
                    className="h-9 gap-1.5 rounded-lg bg-linear-to-br from-violet-500 to-primary px-4 text-xs font-bold text-white shadow-sm transition-[filter] hover:brightness-105">
                    <Pencil className="size-3.5" /> Update
                </Button>
            } />

            {/* Pinned centre pill, same as every other decision screen — the single Good
                Receive button used to sit in the hero and scroll away above the product
                lines it is a verdict on (ui-conventions.md "Decision bar"). */}
            <DecisionBar>
                <span className="text-[12px] font-semibold text-muted-foreground">Quotation #{q.id}</span>
                <div className="flex items-center gap-2.5">
                    <Button
                        type="button"
                        disabled={!canReceive || actionForm.processing}
                        onClick={() => ask('approve', 'Good Receive Quotation?', (c) => runAct('quotations.good-receive.receive', c), true)}
                        className="h-9 px-4 rounded-lg bg-linear-to-br from-violet-500 to-primary text-white font-bold text-xs shadow-sm transition-[filter] hover:brightness-105"
                    >
                        Good Receive
                    </Button>
                </div>
            </DecisionBar>

            {/* Good Receive is a forward move, so the comment is OPTIONAL — the shared rule
                (ui-conventions.md "Decision bar") only makes it mandatory for revise/reject,
                and this page has neither. It lands in quotationassignment.Comment, which is
                exactly what the history popover reads. */}
            <DecisionConfirmDialog
                action={pending?.tone ?? null}
                label={pending?.label}
                showComment={Boolean(pending?.withComment)}
                comment={comment}
                onCommentChange={setComment}
                commentMaxLength={500}
                processing={actionForm.processing || updateForm.processing}
                errors={actionForm.errors}
                onCancel={() => setPending(null)}
                onConfirm={confirmPending}
            />
        </section>
    );
}

QuotationGoodReceiveDetail.layout = [AppLayout]
