import { Link, useForm } from '@inertiajs/react';
import { Fragment, useState } from 'react';
import { ArrowLeft, Ban, Box, Check, ChevronRight, CircleDollarSign, Landmark, Layers, Loader2, Package, Paperclip, Send, Tag, Truck } from 'lucide-react';
import AppLayout from '@/Layouts/AppLayout';
import { Button } from '@/Components/ui/button';
import { StatusBadge } from '@/Components/Proto/UI/StatusBadge';
import { HistoryTimelinePopover } from '@/Components/MenuQuotations/QuotationDetailPage/HistoryTimelinePopover';
import { HistoryPopover } from '@/Components/MenuQuotations/QuotationDetailPage/HistoryPopover';
import { DecisionBar } from '@/Components/MenuSampleOrders/DecisionBar';
import { DecisionConfirmDialog } from '@/Components/MenuSampleOrders/DecisionConfirmDialog';
import { complaintTypeTone, complaintStatusTone } from '@/lib/complaintTone';
import { useToast } from '@/Components/Toast';
import { AttachmentLink } from '@/Components/MenuComplaintAndReturns/AttachmentLink';

// Complaint & Returns — Approval CEO detail + dispatch (Phase 6).
// Sleek, compact, clean implementation following CLAUDE.md design system guidelines.

const DOC_SECTION = 'relative rounded-xl border border-border bg-card px-4 pt-3.5 pb-3.5 shadow-sm';
const DOC_HEADING = 'm-0 mb-3 flex items-center gap-2 text-xs font-bold uppercase tracking-wide text-foreground';
const RING_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';

// Design-system checkbox (proto ApprovalCeoDetail): soft light box when unchecked, flat
// primary purple + white check when checked. Peer pattern, lucide Check.
function AssignCheckbox({ checked, onChange, label }) {
    return (
        <label className="relative inline-flex cursor-pointer items-center justify-center">
            <input type="checkbox" checked={checked} onChange={onChange} aria-label={label} className="peer sr-only" />
            <span aria-hidden="true" className="size-4 rounded-[5px] border border-border/70 bg-card transition-colors peer-checked:border-primary peer-checked:bg-primary peer-hover:border-primary/60 peer-focus-visible:ring-2 peer-focus-visible:ring-primary/40" />
            <Check aria-hidden="true" strokeWidth={3} className="pointer-events-none absolute size-3 text-white opacity-0 transition-opacity peer-checked:opacity-100" />
        </label>
    );
}

// Icon tile + label-over-value field (proto/mockup grammar): a tile leads each GROUP (or
// each field in the order/quantity group); plain fields are label-over-value, borderless.
const TILE = {
    neutral: 'bg-secondary/60 text-foreground/70',
    accent: 'bg-accent text-primary',
    success: 'bg-success-bg text-success-text',
    info: 'bg-info-bg text-info-text',
};
function IconTile({ tint = 'neutral', children }) {
    return <span aria-hidden="true" className={`inline-grid size-10 shrink-0 place-items-center rounded-xl ${TILE[tint]}`}>{children}</span>;
}
function Field({ label, children }) {
    return (
        <div className="min-w-0">
            <span className="block text-[11px] font-medium text-muted-foreground">{label}</span>
            <span className="mt-0.5 block wrap-break-word text-[13px] font-semibold text-foreground">{children ?? '—'}</span>
        </div>
    );
}
function IconField({ icon, tint, label, children }) {
    return (
        <div className="flex min-w-0 items-start gap-3.5">
            <IconTile tint={tint}>{icon}</IconTile>
            <Field label={label}>{children}</Field>
        </div>
    );
}

// "21 May 2026" from a Y-m-d string (mockup's Paid date format).
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const niceDate = (v) => { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(v ?? '')); return m ? `${Number(m[3])} ${MONTHS[Number(m[2]) - 1]} ${m[1]}` : dash(v); };

const dash = (v) => (v === null || v === undefined || v === '' ? '—' : v);
const cleanDept = (dept) => (!dept || dept === 'Unknown (0)' || String(dept).startsWith('Unknown') ? 'General' : dept);
const isZero = (s) => s.startsWith('0000') || s.startsWith('-0001');
const fmtDate = (v) => { if (!v) return '—'; const s = String(v); return isZero(s) ? '—' : s.slice(0, 10); };
const fmtDateTime = (v) => { if (!v) return '—'; const s = String(v); return isZero(s) ? '—' : s.slice(0, 19).replace('T', ' '); };
const fmtN = (v) => (v === null || v === undefined || v === '' || isNaN(Number(v)) ? null : Number(v).toLocaleString('en-US'));
const money = (v) => fmtN(v) ?? '—';
const pair = (qty, unit) => { const n = fmtN(qty); return n === null ? '—' : (unit ? `${n} / ${unit}` : n); };

function Ring({ d }) {
    return (
        <span className={RING_ICON} aria-hidden="true">
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">{d}</svg>
        </span>
    );
}

function DocList({ fields }) {
    return (
        <dl className="grid gap-0">
            {Object.entries(fields).map(([key, val]) => (
                <div key={key} className="grid grid-cols-[minmax(0,130px)_1fr] items-baseline gap-2.5 border-b border-dashed border-border/60 py-1.5 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">{dash(val)}</dd>
                </div>
            ))}
        </dl>
    );
}

export default function Show({ complaint: c, lines, headerHistory = [] }) {
    const { show: showToast } = useToast();
    const [selected, setSelected] = useState({}); // `${lineId}:${dept}` -> instruction string
    const [expanded, setExpanded] = useState({}); // `${lineId}:${dept}` -> bool (instruction row open)
    const [confirmAction, setConfirmAction] = useState(null); // 'assign' | 'reject' | null
    const [rejectComment, setRejectComment] = useState('');
    // CEO's note on the assignment itself, separate from the per-department instructions.
    // Optional — assigning without a note is normal; it lands in complainassignment.Comment,
    // the same column reject() writes its reason to.
    const [assignComment, setAssignComment] = useState('');

    const assignForm = useForm({ selections: [], comment: '' });
    const rejectForm = useForm({ remark: '' });

    const key = (lineId, dept) => `${lineId}:${dept}`;
    const toggle = (lineId, dept) => {
        const k = key(lineId, dept);
        setSelected((s) => {
            const next = { ...s };
            if (k in next) delete next[k];
            else next[k] = '';
            return next;
        });
        // Ticking Assign reveals the instruction layer right away (expand-row UX).
        setExpanded((e) => ({ ...e, [k]: !(k in selected) }));
    };
    const toggleExpand = (lineId, dept) => setExpanded((e) => ({ ...e, [key(lineId, dept)]: !e[key(lineId, dept)] }));
    const setRemark = (lineId, dept, remark) => setSelected((s) => ({ ...s, [key(lineId, dept)]: remark }));

    const submitAssign = () => {
        const selections = Object.entries(selected).map(([k, remark]) => {
            const [lineId, department] = k.split(':');
            return { lineId: Number(lineId), department: Number(department), remark };
        });
        assignForm.transform(() => ({ selections, comment: assignComment }));
        assignForm.post(route('complaints.ceo.assign', c.ID), {
            onError: () => showToast('Please check the form and try again.', 'error'),
            onFinish: () => setConfirmAction(null),
        });
    };

    const submitReject = () => {
        rejectForm.setData('remark', rejectComment);
        rejectForm.transform(() => ({ remark: rejectComment }));
        rejectForm.post(route('complaints.ceo.reject', c.ID), {
            onError: () => showToast('Please check the form and try again.', 'error'),
            onFinish: () => setConfirmAction(null),
        });
    };

    const selectedCount = Object.keys(selected).length;
    const canAssign = selectedCount > 0 && Object.values(selected).every((r) => r.trim() !== '');

    const complaintFields = {
        'Complain Type': c.ComplainTypeName ? <StatusBadge tone={complaintTypeTone(c.ComplainTypeName)}>{c.ComplainTypeName}</StatusBadge> : '—',
        'Complain Reason': dash(c.ComplainReasonName),
        'Complain Date': fmtDate(c.ComplainDate),
        'Input Date': fmtDateTime(c.InputDate),
        'File': <AttachmentLink name={c.UploadName} url={c.FileUrl} />,
        'Details Count': `${lines.length} Line${lines.length === 1 ? '' : 's'}`,
    };

    const companyFields = {
        Company: dash(c.CompanyName),
        'Contact Person': dash(c.CompanyCPName),
        'Company Address': dash(c.CompanyAddress),
        'Company Telephone': dash(c.Telp),
        Division: dash(c.DivisionName),
        Sales: dash(c.Sales),
        Creator: dash(c.Creator),
    };

    const timeline = headerHistory.map((h) => ({
        Status: h.status,
        Tanggal: h.tanggal,
        User: h.user,
        Comment: h.remark,
    }));

    return (
        <section className="flex min-w-0 flex-col gap-4 pb-24">
            {/* Page Header */}
            <header className="flex flex-col items-start gap-3 sm:flex-row sm:items-center sm:justify-between">
                <div className="flex min-w-0 flex-col gap-1">
                    <p className="m-0 flex items-center gap-2 text-xs font-semibold text-muted-foreground">
                        <Link href={route('complaints.ceo.index')} className="text-muted-foreground no-underline hover:text-primary">Approval CEO</Link>
                        <span aria-hidden="true">›</span>
                        <span className="text-foreground">Approve Complaint &amp; Returns Report</span>
                    </p>
                    <div className="flex flex-wrap items-center gap-3">
                        <h1 className="m-0 text-2xl font-extrabold tracking-tight text-foreground">Approval CEO — Report #{c.ID}</h1>
                        {c.ComplainTypeName && (
                            <StatusBadge tone={complaintTypeTone(c.ComplainTypeName)}>{c.ComplainTypeName}</StatusBadge>
                        )}
                        <StatusBadge tone="warning">Awaiting CEO Approval</StatusBadge>
                    </div>
                    <p className="m-0 text-[13px] font-medium text-muted-foreground">
                        {c.CompanyName} · Created on {fmtDateTime(c.InputDate)}
                    </p>
                </div>
                <div className="flex shrink-0 items-center gap-2">
                    <HistoryTimelinePopover entries={timeline} />
                    <Link href={route('complaints.ceo.index')} className={BACK_BTN}>
                        <ArrowLeft className="size-3.5" />
                        Back to List
                    </Link>
                </div>
            </header>

            {/* Document Information Cards */}
            <div className="grid grid-cols-2 gap-3.5 max-[860px]:grid-cols-1">
                <section className={DOC_SECTION}>
                    <h3 className={DOC_HEADING}>
                        <Ring d={<><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" /></>} />
                        Complaint Information
                    </h3>
                    <DocList fields={complaintFields} />
                </section>
                <section className={DOC_SECTION}>
                    <h3 className={DOC_HEADING}>
                        <Ring d={<><path d="M3 21h18" /><path d="M5 21V7l7-4 7 4v14" /><path d="M9 9h.01" /><path d="M9 13h.01" /><path d="M9 17h.01" /><path d="M15 9h.01" /><path d="M15 13h.01" /><path d="M15 17h.01" /></>} />
                        Company &amp; Contact
                    </h3>
                    <DocList fields={companyFields} />
                </section>
            </div>

            {/* Per-Line Cards — proto ApprovalCeoDetail layout, real data */}
            {lines.map((line) => {
                const lineHistory = line.history ?? [];

                return (
                    <section key={line.ID} className={DOC_SECTION}>
                        {/* Line title: product as the hero */}
                        <div className="flex flex-wrap items-center justify-between gap-2 border-b border-border/50 pb-2.5">
                            <h3 className="m-0 flex flex-wrap items-center gap-2.5">
                                <span className="text-[16px] font-extrabold tracking-tight text-foreground">{dash(line.ProductName)}</span>
                                <span aria-hidden="true" className="text-border-strong">·</span>
                                <span className="text-[14px] font-medium text-muted-foreground">{dash(line.PrincipalName)}</span>
                                <span className="rounded-full bg-secondary px-2.5 py-0.5 text-[11px] font-semibold text-muted-foreground">Line #{line.ID}</span>
                            </h3>
                            <HistoryPopover count={lineHistory.length} title={`History — ${line.ProductName}`} width={380}>
                                {lineHistory.map((h, i) => (
                                    <div key={i} className="flex flex-col gap-0.5 border-b border-border/50 py-1.5 last:border-b-0">
                                        <div className="flex items-center justify-between gap-2">
                                            <div className="flex items-center gap-1.5">
                                                <StatusBadge tone={complaintStatusTone(h.status)}>{dash(h.status)}</StatusBadge>
                                                <span className="text-[10px] font-bold text-foreground/80">{cleanDept(h.department)}</span>
                                            </div>
                                            <span className="shrink-0 text-[10px] font-medium tabular-nums text-muted-foreground">{fmtDateTime(h.tanggal)}</span>
                                        </div>
                                        <span className="text-[11px] leading-snug text-muted-foreground">
                                            <span className="font-semibold text-foreground">{dash(h.user)}</span>
                                            {h.remark ? ` · ${h.remark}` : ''}
                                        </span>
                                    </div>
                                ))}
                            </HistoryPopover>
                        </div>

                        {/* Description — accent bar, plain lines (mockup) */}
                        {(line.ComplainDesc || line.CustomerExpectation || line.ReporterRequestExpectation) && (
                            <div className="mt-4 border-l-2 border-primary pl-3.5">
                                {line.ComplainDesc && <p className="m-0 text-[13px] font-medium text-foreground">{line.ComplainDesc}</p>}
                                {(line.CustomerExpectation || line.ReporterRequestExpectation) && (
                                    <p className="m-0 mt-0.5 text-[13px] text-muted-foreground">
                                        {line.CustomerExpectation}
                                        {line.CustomerExpectation && line.ReporterRequestExpectation && <span aria-hidden="true" className="mx-1.5 text-border-strong">•</span>}
                                        {line.ReporterRequestExpectation}
                                    </p>
                                )}
                            </div>
                        )}

                        {/* Transaction info — two halves with a vertical divider (mockup) */}
                        <div className="mt-5 grid gap-8 border-t border-border/60 pt-5 lg:grid-cols-2 lg:gap-0 lg:divide-x lg:divide-border/60">
                            {/* Left: order & quantity (a tile per field) + pricing */}
                            <div className="lg:pr-8">
                                <div className="grid grid-cols-2 gap-x-6 gap-y-5">
                                    <IconField icon={<Layers className="size-4" />} label="Application">{dash(line.ApplicationName)}</IconField>
                                    <IconField icon={<Package className="size-4" />} label="Qty Packing">{pair(line.QuantityPacking, line.SatuanPackingName)}</IconField>
                                    <IconField icon={<Tag className="size-4" />} label="Lot Number">{dash(line.LotNumber)}</IconField>
                                    <IconField icon={<Box className="size-4" />} label="Complain Qty">{pair(line.ComplainQuantity, line.SatuanComplainName)}</IconField>
                                </div>
                                <div className="mt-5 flex gap-3.5 border-t border-border/60 pt-5">
                                    <IconTile tint="accent"><CircleDollarSign className="size-4" /></IconTile>
                                    <div className="grid min-w-0 flex-1 grid-cols-3 gap-x-6 gap-y-5 max-[560px]:grid-cols-2">
                                        <Field label="USD Rate">{money(line.USDRate)}</Field>
                                        <Field label="Unit Price USD">{pair(line.UnitPriceUSD, line.SatuanUnitPriceUSDName)}</Field>
                                        <Field label="Total Value USD">{money(line.TotalValueUSD)}</Field>
                                        <Field label="Total Value IDR">{money(line.TotalValueIDR)}</Field>
                                        <Field label="Unit Price IDR">{money(line.UnitPriceIDR)}</Field>
                                    </div>
                                </div>
                            </div>

                            {/* Right: shipping & invoice + bank / refund */}
                            <div className="max-lg:border-t max-lg:border-border/60 max-lg:pt-5 lg:pl-8">
                                <div className="flex gap-3.5">
                                    <IconTile tint="success"><Truck className="size-4" /></IconTile>
                                    <div className="grid min-w-0 flex-1 grid-cols-2 gap-x-6 gap-y-5">
                                        <Field label="SJ No">{dash(line.SJNo)}</Field>
                                        <Field label="SJ Date">{fmtDate(line.SJDate)}</Field>
                                        <Field label="Invoice No">{dash(line.InvoiceNo)}</Field>
                                        <Field label="Invoice Date">{fmtDate(line.InvoiceDate)}</Field>
                                    </div>
                                </div>
                                <div className="mt-5 flex gap-3.5 border-t border-border/60 pt-5">
                                    <IconTile tint="info"><Landmark className="size-4" /></IconTile>
                                    <div className="grid min-w-0 flex-1 grid-cols-2 gap-x-6 gap-y-5">
                                        <Field label="Bank / Account">{line.BankName ? `${line.BankName} - ${line.BankAccountName || '—'}` : '—'}</Field>
                                        <Field label="Account No">{dash(line.BankAccountNumber)}</Field>
                                        <Field label="Total Refund">{money(line.TotalRefund)}</Field>
                                        <Field label="Status">
                                            {line.IsPaid ? (
                                                <span className="inline-flex items-center gap-1.5">
                                                    <span aria-hidden="true" className="size-1.5 rounded-full bg-success" />
                                                    Paid
                                                    <span aria-hidden="true" className="text-border-strong">·</span>
                                                    <span className="font-medium text-muted-foreground">{niceDate(line.PaidDate)}</span>
                                                </span>
                                            ) : 'Unpaid'}
                                        </Field>
                                    </div>
                                </div>
                            </div>
                        </div>

                        {/* Assign — clean list (Department · Remark-as-hero · File) + EXPAND ROW for
                            the instruction. Rule: list = fast scanning; detail (instruction) = on demand. */}
                        <div className="mt-5 overflow-x-auto border-t border-border/60">
                            <table className="w-full border-separate border-spacing-0 [&_thead_th]:whitespace-nowrap [&_thead_th]:border-b [&_thead_th]:border-border/60 [&_thead_th]:px-3.5 [&_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 [&_tbody_td]:px-3.5 [&_tbody_td]:align-middle [&_tbody_td]:text-[12px] [&_tbody_td]:text-card-foreground">
                                <thead>
                                    <tr>
                                        <th className="w-12"><span className="sr-only">Assign</span></th>
                                        <th className="w-[170px]">Department</th>
                                        <th>Remark</th>
                                        <th className="w-[150px]">File</th>
                                        <th className="w-10"><span className="sr-only">Detail</span></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {line.actions.map((a) => {
                                        const k = key(line.ID, a.DepartmentID);
                                        const isSelected = k in selected;
                                        const isOpen = !!expanded[k];
                                        return (
                                            <Fragment key={a.ID}>
                                                <tr onClick={() => toggleExpand(line.ID, a.DepartmentID)}
                                                    className={`cursor-pointer transition-colors hover:[&_td]:bg-secondary/30 ${isOpen ? '[&_td]:bg-secondary/20' : ''}`}>
                                                    <td onClick={(e) => e.stopPropagation()} className={`py-3 text-center ${isOpen ? '' : 'border-b border-border/40'}`}>
                                                        <AssignCheckbox checked={isSelected} onChange={() => toggle(line.ID, a.DepartmentID)} label={`Assign ${a.DepartmentName}`} />
                                                    </td>
                                                    <td className={`py-3 ${isOpen ? '' : 'border-b border-border/40'}`}>
                                                        <span className="inline-flex items-center rounded-full bg-secondary px-3 py-1 text-[11.5px] font-bold text-foreground">{a.DepartmentName}</span>
                                                    </td>
                                                    {/* Remark = the hero of the row */}
                                                    <td className={`py-3 font-medium text-foreground ${isOpen ? '' : 'border-b border-border/40'}`}>{a.ReviewRemark || '—'}</td>
                                                    <td className={`py-3 ${isOpen ? '' : 'border-b border-border/40'}`}>
                                                        <span className="inline-flex items-center gap-1.5 text-[12px] text-muted-foreground">
                                                            <Paperclip className="size-3.5" aria-hidden="true" />
                                                            {a.UploadName || 'No file'}
                                                        </span>
                                                    </td>
                                                    <td className={`py-3 text-right ${isOpen ? '' : 'border-b border-border/40'}`}>
                                                        <ChevronRight aria-hidden="true"
                                                            className={`size-4 text-muted-foreground transition-transform duration-150 ${isOpen ? 'rotate-90 text-primary' : ''}`} />
                                                    </td>
                                                </tr>
                                                {/* Expand layer — instruction on demand. Skips the checkbox +
                                                    department cells so the block starts flush with the Remark column. */}
                                                {isOpen && (
                                                    <tr>
                                                        <td className="border-b border-border/40 !py-0" aria-hidden="true" />
                                                        <td className="border-b border-border/40 !py-0" aria-hidden="true" />
                                                        <td colSpan={3} className="border-b border-border/40 !py-0">
                                                            <div className="mb-3 max-w-xl" onClick={(e) => e.stopPropagation()}>
                                                                <span className="block text-[10.5px] font-bold uppercase tracking-wide text-muted-foreground">Instruction</span>
                                                                {isSelected ? (
                                                                    <input type="text" value={selected[k]} autoFocus
                                                                        onChange={(e) => setRemark(line.ID, a.DepartmentID, e.target.value)}
                                                                        placeholder="Write the instruction for this department…"
                                                                        className="mt-1.5 h-9 w-full rounded-md border border-input bg-card px-3 text-[12.5px] text-foreground outline-none transition-colors focus:border-primary focus:ring-1 focus:ring-primary placeholder:text-muted-foreground/60" />
                                                                ) : (
                                                                    <p className="m-0 mt-1 text-[12px] text-muted-foreground">Tick <strong className="font-semibold text-foreground">Assign</strong> to write an instruction for {a.DepartmentName}.</p>
                                                                )}
                                                            </div>
                                                        </td>
                                                    </tr>
                                                )}
                                            </Fragment>
                                        );
                                    })}
                                </tbody>
                            </table>
                        </div>
                    </section>
                );
            })}

            {/* Floating Decision Bar */}
            <DecisionBar>
                {selectedCount > 0 ? (
                    <span className="text-xs font-semibold text-muted-foreground">
                        <strong className="text-foreground">{selectedCount}</strong> department assignment{selectedCount === 1 ? '' : 's'} selected
                    </span>
                ) : (
                    <span className="text-xs font-medium text-muted-foreground">
                        Select department assignments to proceed
                    </span>
                )}
                <div className="flex items-center gap-2.5">
                    <Button
                        type="button"
                        variant="outline"
                        onClick={() => setConfirmAction('reject')}
                        className="h-9 gap-1.5 rounded-lg border-danger/40 text-xs font-bold text-danger hover:bg-danger/10"
                    >
                        <Ban className="size-3.5" />
                        Reject Complaint
                    </Button>
                    <Button
                        type="button"
                        disabled={!canAssign || assignForm.processing}
                        onClick={() => setConfirmAction('assign')}
                        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"
                    >
                        {assignForm.processing ? <Loader2 className="size-3.5 animate-spin" /> : <Send className="size-3.5" />}
                        Assign to Departments
                    </Button>
                </div>
            </DecisionBar>

            {/* Confirmation Dialogs */}
            {/* The comment is OPTIONAL here (commentRequired={false}) but must be wired: the
                textarea is controlled, so without both `comment` and `onCommentChange` the
                onChange no-ops and React resets it to '' on every keystroke — it looks broken.
                It travels beside `selections` and is stored on complainassignment.Comment. */}
            {confirmAction === 'assign' && (
                <DecisionConfirmDialog
                    action="approve"
                    label="Confirm Department Assignment"
                    onCancel={() => setConfirmAction(null)}
                    onConfirm={submitAssign}
                    processing={assignForm.processing}
                    comment={assignComment}
                    onCommentChange={setAssignComment}
                    commentRequired={false}
                    error={assignForm.errors.comment}
                    summary={
                        <div className="rounded-lg border border-border bg-accent/30 p-3 text-[12px] text-foreground">
                            <p className="m-0 font-semibold text-primary">
                                Assigning complaint to {selectedCount} department{selectedCount === 1 ? '' : 's'}:
                            </p>
                            <ul className="m-0 mt-1.5 flex flex-col gap-1 pl-4 text-muted-foreground">
                                {Object.entries(selected).map(([k, rem]) => {
                                    const [lId, dId] = k.split(':');
                                    const lineObj = lines.find((l) => String(l.ID) === lId);
                                    const actionObj = lineObj?.actions.find((a) => String(a.DepartmentID) === dId);
                                    return (
                                        <li key={k}>
                                            <span className="font-bold text-foreground">{actionObj?.DepartmentName}</span> (Line {lineObj?.ProductName}): "{rem}"
                                        </li>
                                    );
                                })}
                            </ul>
                        </div>
                    }
                />
            )}

            {confirmAction === 'reject' && (
                <DecisionConfirmDialog
                    action="reject"
                    label="Reject Complaint Report"
                    onCancel={() => setConfirmAction(null)}
                    onConfirm={submitReject}
                    comment={rejectComment}
                    onCommentChange={setRejectComment}
                    processing={rejectForm.processing}
                    error={rejectForm.errors.remark}
                    commentRequired={true}
                />
            )}
        </section>
    );
}

Show.layout = [AppLayout];
