// General Affairs — "View All" admin detail (Phase 6, 2026-07-24).
// Admin view of any request with Cancel (1/2/3 → 10), Revise (8 → cancel-and-clone) and the
// arbitrary status-override "Change" (any status + required comment) — legacy
// vehiclerequestdetailsall.php via VehicleServiceRequestController@viewAllShow/cancel/change.
import { useState } from 'react';
import { Link, router } from '@inertiajs/react';
import { ArrowLeft, Car, ClipboardList, ListOrdered, Loader2, RefreshCw, Shuffle } 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 { Button } from '@/Components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/Components/ui/dialog';
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 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 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 ViewAllDetail({ request, lines, history, statusOptions = [], canCancel = false, canRevise = false }) {
    const vsr = request;
    const vehicle = request.vehicle;
    const { show: showToast } = useToast();

    const [cancelOpen, setCancelOpen] = useState(false);
    const [changeOpen, setChangeOpen] = useState(false);
    const [comment, setComment] = useState('');
    const [changeStatus, setChangeStatus] = useState('');
    const [processing, setProcessing] = useState(false);

    const openCancel = () => { setComment(''); setCancelOpen(true); };
    const openChange = () => { setComment(''); setChangeStatus(''); setChangeOpen(true); };
    const goRevise = () => router.visit(route('general-affairs.revise.create', vsr.id));

    const doCancel = () => run(route('general-affairs.cancel', vsr.id), { comment }, () => setCancelOpen(false));
    const doChange = () => {
        if (!changeStatus) { showToast('Please select a status.', 'warning'); return; }
        if (!comment.trim()) { showToast('Please enter a comment.', 'warning'); return; }
        run(route('general-affairs.change', vsr.id), { status: changeStatus, comment }, () => setChangeOpen(false));
    };

    const run = (url, payload, onDone) => {
        setProcessing(true);
        router.post(url, payload, {
            preserveScroll: true,
            onSuccess: () => onDone(),
            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;
    const settlementFields = {
        'Down Payment': `Rp ${Number(vsr.totalCashBon ?? 0).toLocaleString('en-US', { minimumFractionDigits: 2 })}`,
        'Total Payment': `Rp ${Number(vsr.totalPayment ?? 0).toLocaleString('en-US', { minimumFractionDigits: 2 })}`,
        'Total Balance': `Rp ${Number(vsr.totalBalance ?? 0).toLocaleString('en-US', { minimumFractionDigits: 2 })}`,
    };

    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.view-all')} className="text-foreground no-underline hover:text-primary">View All</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.view-all')} 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">View All — 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"><ListOrdered className="size-3.5" /></span>Settlement</h3>
                    <DocList fields={settlementFields} />
                </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-[1040px]`}>
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Service Type</th>
                                    <th>Service Date</th>
                                    <th>Status</th>
                                    <th>Brand</th>
                                    <th>Place</th>
                                    <th className="number">Est. Price</th>
                                    <th className="number">Fixed Price</th>
                                    <th>Remark</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 className="tabular-nums">{d.detailStatus}</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><Prose>{d.remark}</Prose></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.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={openChange} className={`${BAR_BTN} bg-linear-to-br from-violet-500 to-primary text-white shadow-sm hover:brightness-105`}>
                        <Shuffle className="mr-1.5 size-3.5" /> Change Status
                    </button>
                    {canRevise && (
                        <button type="button" onClick={goRevise} className={`${BAR_BTN} border border-input bg-card text-primary hover:border-primary`}>
                            <RefreshCw className="mr-1.5 size-3.5" /> Revise
                        </button>
                    )}
                    {canCancel && (
                        <button type="button" onClick={openCancel} className={`${BAR_BTN} border border-danger/40 bg-card text-danger hover:bg-danger/10`}>Cancel</button>
                    )}
                </div>
            </DecisionBar>

            <DecisionConfirmDialog
                action={cancelOpen ? 'reject' : null}
                label="Cancel Request"
                comment={comment}
                onCommentChange={setComment}
                processing={processing}
                commentRequired={false}
                onCancel={() => setCancelOpen(false)}
                onConfirm={doCancel}
            />

            {/* Admin status override — dedicated dialog (its own "Change Status" verb). */}
            <Dialog open={changeOpen} onOpenChange={(open) => { if (!open) setChangeOpen(false); }}>
                <DialogContent className="bg-card sm:max-w-md">
                    <DialogHeader>
                        <DialogTitle>Change Status</DialogTitle>
                        <DialogDescription>Override this request's status. The header and its lines move to the chosen status.</DialogDescription>
                    </DialogHeader>

                    <label className="block">
                        <span className="mb-1.5 block text-[12px] font-semibold text-muted-foreground">New status <span className="text-danger-text">*</span></span>
                        <select value={changeStatus} onChange={(e) => setChangeStatus(e.target.value)}
                            className="h-9 w-full rounded-md border border-input bg-card px-2.5 text-[13px] text-foreground outline-none transition-colors focus:border-primary">
                            <option value="">Select status…</option>
                            {statusOptions.map((s) => <option key={s.id} value={s.id}>{s.id} · {s.name}</option>)}
                        </select>
                    </label>

                    <label className="block">
                        <span className="mb-1.5 block text-[12px] font-semibold text-muted-foreground">Comment <span className="text-danger-text">*</span></span>
                        <textarea value={comment} onChange={(e) => setComment(e.target.value)} rows={3} autoFocus placeholder="Reason for this change…"
                            className="w-full resize-y rounded-lg border border-input bg-card px-3 py-2.5 text-[13px] text-foreground outline-none transition-colors focus:border-primary" />
                    </label>

                    <DialogFooter>
                        <Button type="button" disabled={processing || !changeStatus || !comment.trim()} onClick={doChange}
                            className="bg-linear-to-br from-violet-500 to-primary font-bold text-white hover:brightness-105">
                            {processing ? <Loader2 className="mr-2 size-4 animate-spin" /> : null}
                            Change Status
                        </Button>
                        <Button type="button" variant="outline" disabled={processing} onClick={() => setChangeOpen(false)}>Cancel</Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </section>
    );
}

ViewAllDetail.layout = [AppLayout];
