// General Affairs — "Finance Payment" detail (Phase 5, 2026-07-24).
// Built on the frozen GA detail grammar (FinanceDpDetail). Finance records the settlement:
// Total Payment (editable, default Σ FixedPrice) and Total Balance (Total Payment − Down
// Payment) → "Finance Payment" writes status 6 (VehicleServiceRequestController@financePaymentAct).
// Rejected lines stay pink. Revise → 8.
import { useMemo, useState } from 'react';
import { Link, router } from '@inertiajs/react';
import { ArrowLeft, Car, ClipboardList, ListOrdered, Wallet } from 'lucide-react';
import AppLayout from '@/Layouts/AppLayout';
import { StatusBadge } from '@/Components/Proto/UI/StatusBadge';
import { HistoryPopover } from '@/Components/MenuQuotations/QuotationDetailPage/HistoryPopover';
import { HistoryTimelinePopover } from '@/Components/MenuQuotations/QuotationDetailPage/HistoryTimelinePopover';
import { DecisionBar } from '@/Components/MenuSampleOrders/DecisionBar';
import { DecisionConfirmDialog } from '@/Components/MenuSampleOrders/DecisionConfirmDialog';
import { PrintReportButton } from '@/Components/MenuGeneralAffairs/PrintReportButton';
import { useToast } from '@/Components/Toast';

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';

const BAR_BTN = 'inline-flex h-9 flex-1 items-center justify-center whitespace-nowrap rounded-lg px-3.5 text-xs font-bold transition-colors sm:flex-none';
const BAR_BTN_PRIMARY = 'inline-flex h-9 flex-1 items-center justify-center whitespace-nowrap rounded-lg bg-linear-to-br from-violet-500 to-primary px-3.5 text-xs font-bold text-white shadow-sm transition-[filter] hover:brightness-105 sm:flex-none';

const DETAIL_TABLE =
    'w-full border-separate border-spacing-0 ' +
    '[&_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/80 ' +
    '[&_th:first-child]:pl-[22px] [&_td:first-child]:pl-[22px] [&_th:last-child]:pr-5 [&_td:last-child]:pr-5 ' +
    '[&_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]:align-top [&_tbody_td]:text-[12px] [&_tbody_td]:font-medium [&_tbody_td]:text-foreground [&_tbody_tr:last-child_td]:border-b-0 ' +
    '[&_tbody_tr:nth-child(even)_td]:bg-secondary/25 [&_tbody_tr:hover_td]:bg-secondary/60';

const STATUS_TONE = {
    'Request': 'primary', 'Review GA': 'warning', 'Approval GA': 'success', 'Finance Down Payment': 'primary',
    'GA Processing': 'primary', 'Finance Settlement': 'primary', 'GA Completion': 'success',
    'Revise': 'warning', 'Reject': 'danger', 'Cancel': 'danger', 'Re-Review': 'warning',
};
const statusTone = (name) => STATUS_TONE[name] ?? 'neutral';
const fmtNum = (v) => (v == null || v === '' ? '—' : Number(v).toLocaleString('en-US', { minimumFractionDigits: 2 }));
const fmtMoney = (v) => `Rp ${Number(v ?? 0).toLocaleString('en-US', { minimumFractionDigits: 2 })}`;
const fmtCurrencyInput = (v) => {
    const raw = String(v ?? '').replace(/[^\d.]/g, '');
    const [int, ...rest] = raw.split('.');
    const grouped = (int || '').replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    return rest.length ? `${grouped}.${rest.join('')}` : grouped;
};
const filled = (v) => v != null && String(v).trim() !== '' && v !== '—';
const Prose = ({ children }) =>
    filled(children) ? <span className="block min-w-44 max-w-72 whitespace-normal break-words leading-relaxed">{children}</span> : '—';

function DocList({ fields, columns = 1 }) {
    if (!fields || Object.keys(fields).length === 0)
        return <p className="px-0 py-1 text-[0.82rem] text-muted-foreground">No data.</p>;
    if (columns === 2) {
        return (
            <dl className="grid grid-cols-2 gap-x-4 gap-y-0 [&>div:nth-last-child(-n+2)]:border-b-0 max-[520px]:grid-cols-1">
                {Object.entries(fields).map(([key, val]) => (
                    <div key={key} className="border-b border-border/40 py-1.75">
                        <dt className="m-0 text-[11px] font-medium text-muted-foreground">{key}</dt>
                        <dd className="m-0 mt-0.5 wrap-break-word text-xs font-medium text-foreground">{val || '—'}</dd>
                    </div>
                ))}
            </dl>
        );
    }
    return (
        <dl className="grid gap-0">
            {Object.entries(fields).map(([key, val]) => (
                <div key={key} className="grid grid-cols-[minmax(0,120px)_1fr] items-baseline gap-2.5 border-b border-border/40 py-1.75 last:border-b-0">
                    <dt className="m-0 text-[11px] font-medium text-muted-foreground">{key}</dt>
                    <dd className="m-0 wrap-break-word text-xs font-medium text-foreground">{val || '—'}</dd>
                </div>
            ))}
        </dl>
    );
}

export default function FinancePaymentDetail({ request, lines, history }) {
    const vsr = request;
    const vehicle = request.vehicle;
    const { show: showToast } = useToast();

    const cashBon = Number(vsr.totalCashBon ?? 0);
    // Total Payment — editable, seeded from Σ FixedPrice (legacy default).
    const [payment, setPayment] = useState(() => fmtCurrencyInput(String(vsr.sumFixedPrice ?? 0)));
    // Balance = Payment − Down Payment (definition; PRD §8), recomputed live.
    const balance = useMemo(() => Number(String(payment).replace(/,/g, '') || 0) - cashBon, [payment, cashBon]);

    const [decision, setDecision] = useState(null);
    const [comment, setComment] = useState('');
    const [processing, setProcessing] = useState(false);
    const pick = (dialogAction, routeAction, label) => { setComment(''); setDecision({ dialogAction, routeAction, label }); };

    const confirm = () => {
        if (!decision) return;
        if (decision.routeAction === 'settle') {
            if (!String(payment).trim()) { showToast('Enter the payment amount.', 'warning'); return; }
            post('settle', {
                total_payment: String(payment).replace(/,/g, ''),
                total_balance: String(balance),
                comment,
            });
        } else {
            post('revise', { comment });
        }
    };

    const post = (routeAction, payload) => {
        setProcessing(true);
        router.post(route('general-affairs.finance-payment.act', [vsr.id, routeAction]), payload, {
            preserveScroll: true,
            onSuccess: () => setDecision(null),
            onError: () => showToast('Please check the form and try again.', 'error'),
            onFinish: () => setProcessing(false),
        });
    };

    const requestFields = {
        'No': vsr.id,
        'Created Date': vsr.tanggal || '—',
        'Status': vsr.statusName || '—',
        'Creator': vsr.creator || '—',
        'Owner': vsr.owner || '—',
        'KM': filled(vsr.km) ? `${vsr.km} KM` : '—',
        'Req Remark': vsr.remark || '—',
        'Download File': vsr.hasUpload
            ? <a href={vsr.uploadUrl} className="font-semibold text-primary hover:underline">{vsr.uploadName || 'Download'}</a>
            : 'No File',
        'GA Document': vsr.hasGaUpload
            ? <a href={vsr.gaUploadUrl} className="font-semibold text-primary hover:underline">{vsr.gaUploadName || 'Download'}</a>
            : 'No File',
    };
    const vehicleFields = vehicle ? {
        'Brand Name': vehicle.brandName || '—',
        'Brand Type': vehicle.brandType || '—',
        'Color': vehicle.color || '—',
        'Production Year': vehicle.productionYear || '—',
        'Lisence Plate': vehicle.plate || '—',
        'Lisence Expiry Date': vehicle.licenseExpiry || '—',
        'Insurance': vehicle.insurance || '—',
        'Insurance Expiry Date': vehicle.insuranceExpiry || '—',
        'Chassis Number': vehicle.chassisNumber || '—',
        'Engine Number': vehicle.engineNumber || '—',
        'Vehicle Desc': vehicle.description || '—',
    } : null;

    return (
        <section className="flex min-w-0 flex-col gap-4.5">
            <header className="flex flex-wrap items-start justify-between gap-3">
                <div>
                    <p className="mb-1.5 flex items-center gap-2 text-xs font-semibold text-muted-foreground">
                        <span>General Affair</span>
                        <span aria-hidden="true">›</span>
                        <Link href={route('general-affairs.finance-payment')} className="text-foreground no-underline hover:text-primary">Finance Payment</Link>
                    </p>
                </div>
                <div className="flex items-center gap-2">
                    <PrintReportButton request={request} lines={lines} history={history} />
                    <HistoryTimelinePopover entries={(history ?? []).map((h) => ({ Status: h.statusName || '—', Tanggal: h.tanggal || '—', User: h.userName || '—', Comment: h.comment || '' }))}
                        label="History"
                        triggerClassName="border-input bg-card text-foreground hover:border-primary hover:text-primary" />
                    <Link href={route('general-affairs.finance-payment')} className={BACK_BTN}>
                        <ArrowLeft className="size-3.5" /> Back to List
                    </Link>
                </div>
            </header>

            <div className="mt-1 flex items-center justify-between gap-4">
                <div className="flex min-w-0 flex-col gap-1">
                    <div className="flex flex-wrap items-center gap-3">
                        <h1 className="m-0 text-2xl font-extrabold tracking-tight text-foreground max-[560px]:text-xl">Finance Payment — Vehicle Service Request #{vsr.id}</h1>
                        {vsr.statusName && <StatusBadge tone={statusTone(vsr.statusName)}>{vsr.statusName}</StatusBadge>}
                    </div>
                    {vsr.tanggal && <p className="m-0 text-[12px] font-medium text-muted-foreground">Created on {vsr.tanggal}</p>}
                </div>
            </div>

            <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="request">
                    <h3 className={DOC_HEADING}><span className={DOC_ICON} aria-hidden="true"><ClipboardList className="size-3.5" /></span>Request Information</h3>
                    <DocList fields={requestFields} />
                </section>
                <section className={DOC_SECTION} data-section-id="vehicle">
                    <h3 className={DOC_HEADING}><span className={DOC_ICON} aria-hidden="true"><Car className="size-3.5" /></span>Vehicle</h3>
                    <DocList fields={vehicleFields} columns={2} />
                </section>
                <section className={DOC_SECTION} data-section-id="settlement">
                    <h3 className={DOC_HEADING}><span className={DOC_ICON} aria-hidden="true"><Wallet className="size-3.5" /></span>Settlement</h3>
                    <dl className="grid gap-0">
                        <div className="grid grid-cols-[minmax(0,130px)_1fr] items-baseline gap-2.5 border-b border-border/40 py-1.75">
                            <dt className="m-0 text-[11px] font-medium text-muted-foreground">Total Fixed Price</dt>
                            <dd className="m-0 text-xs font-semibold tabular-nums text-foreground">{fmtMoney(vsr.sumFixedPrice)}</dd>
                        </div>
                        <div className="grid grid-cols-[minmax(0,130px)_1fr] items-baseline gap-2.5 border-b border-border/40 py-1.75">
                            <dt className="m-0 text-[11px] font-medium text-muted-foreground">Down Payment</dt>
                            <dd className="m-0 text-xs font-medium tabular-nums text-muted-foreground">{fmtMoney(cashBon)}</dd>
                        </div>
                        <div className="grid grid-cols-[minmax(0,130px)_1fr] items-center gap-2.5 border-b border-border/40 py-1.75">
                            <dt className="m-0 text-[11px] font-medium text-muted-foreground">Total Payment</dt>
                            <dd className="m-0">
                                <div className="relative">
                                    <span className="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-[11px] font-medium text-muted-foreground">Rp</span>
                                    <input type="text" inputMode="numeric" value={payment}
                                        onChange={(e) => setPayment(fmtCurrencyInput(e.target.value))}
                                        aria-label="Total payment"
                                        className="h-9 w-full rounded-md border border-input bg-card pl-8 pr-2 text-right text-[12px] font-semibold tabular-nums text-foreground outline-none transition-colors focus-visible:border-primary" />
                                </div>
                            </dd>
                        </div>
                        <div className="grid grid-cols-[minmax(0,130px)_1fr] items-baseline gap-2.5 py-1.75">
                            <dt className="m-0 text-[11px] font-medium text-muted-foreground">Total Balance</dt>
                            <dd className="m-0 text-xs font-bold tabular-nums text-primary">{fmtMoney(balance)}</dd>
                        </div>
                    </dl>
                </section>
            </div>

            <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"><ListOrdered className="size-3.5" /></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>Details List</h2>
                            <small>Service line items breakdown</small>
                        </div>
                    </div>
                </header>

                {lines.length === 0 ? (
                    <p className="p-6 text-[0.85rem] text-muted-foreground">No line items.</p>
                ) : (
                    <div className="overflow-x-auto rounded-b-2xl">
                        <table className={`${DETAIL_TABLE} min-w-[980px]`}>
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Service Type</th>
                                    <th>Service Date</th>
                                    <th>Brand</th>
                                    <th>Place</th>
                                    <th className="number">Est. Price</th>
                                    <th className="number">Fixed Price</th>
                                    <th>Fixed Guarantee</th>
                                    <th>Remark</th>
                                    <th className="!text-center">Historical</th>
                                    <th className="!text-center">History</th>
                                </tr>
                            </thead>
                            <tbody>
                                {lines.map((d) => (
                                    <tr key={d.id} className={d.isRejected ? '[&>td]:!bg-destructive/5' : undefined}>
                                        <td className="tabular-nums">{d.id}</td>
                                        <td>{d.typeName || '—'}</td>
                                        <td className="tabular-nums">{d.serviceDate || '—'}</td>
                                        <td>{d.brand || '—'}</td>
                                        <td>{d.place || '—'}</td>
                                        <td className="number tabular-nums">{fmtNum(d.estimatedPrice)}</td>
                                        <td className="number tabular-nums">{fmtNum(d.fixedPrice)}</td>
                                        <td>{d.fixedGuarantee || '—'}</td>
                                        <td><Prose>{d.remark}</Prose></td>
                                        <td className="text-center">
                                            <HistoryPopover count={(d.historical ?? []).length} title="Historical Service" width={320}>
                                                {(d.historical ?? []).map((s, i) => (
                                                    <div key={i} className="text-[11px] leading-snug text-muted-foreground">
                                                        <span className="font-semibold text-foreground">{s.brand || '—'} ({s.place || '—'})</span>{' · '}
                                                        <span className="tabular-nums">{fmtNum(s.fixedPrice)}</span>
                                                    </div>
                                                ))}
                                            </HistoryPopover>
                                        </td>
                                        <td className="text-center">
                                            <HistoryPopover count={(d.history ?? []).length} title="History" width={320}>
                                                {(d.history ?? []).map((h, i) => (
                                                    <div key={i} className="text-[11px] leading-snug text-muted-foreground">
                                                        <span className="font-semibold text-foreground">{h.statusName || '—'}</span>
                                                        {h.tanggal ? <> · <span className="tabular-nums">{h.tanggal}</span></> : null}
                                                        {h.userName ? ` · ${h.userName}` : ''}
                                                        {h.brand ? ` · ${h.brand}` : ''}
                                                        {h.remark ? ` · ${h.remark}` : ''}
                                                    </div>
                                                ))}
                                            </HistoryPopover>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}
            </article>


            <DecisionBar>
                <span className="hidden whitespace-nowrap text-[12.5px] font-semibold text-muted-foreground sm:inline">
                    Request <span className="font-extrabold text-foreground">#{vsr.id}</span> · {vsr.statusName}
                </span>
                <div className="flex w-full flex-wrap items-center gap-2 sm:w-auto sm:flex-nowrap">
                    <button type="button" onClick={() => pick('approve', 'settle', 'Finance Payment')} className={BAR_BTN_PRIMARY}>Finance Payment</button>
                    <button type="button" onClick={() => pick('revise', 'revise', 'Revise')} className={`${BAR_BTN} border border-input bg-card text-warning-text hover:border-warning`}>Revise</button>
                </div>
            </DecisionBar>

            <DecisionConfirmDialog
                action={decision?.dialogAction ?? null}
                label={decision?.label}
                comment={comment}
                onCommentChange={setComment}
                processing={processing}
                onCancel={() => setDecision(null)}
                onConfirm={confirm}
            />
        </section>
    );
}

FinancePaymentDetail.layout = [AppLayout];
