import { Link } from '@inertiajs/react'
import { ArrowLeft } from 'lucide-react'
import { StatusBadge } from '@/Components/Proto/UI/StatusBadge'
import { HistoryPopover } from '@/Components/MenuQuotations/QuotationDetailPage/HistoryPopover'
import { HistoryTimelinePopover } from '@/Components/MenuQuotations/QuotationDetailPage/HistoryTimelinePopover'
import { complaintStatusTone, complaintTypeTone } from '@/lib/complaintTone'
import { AttachmentLink } from '@/Components/MenuComplaintAndReturns/AttachmentLink'

// Complaint & Returns — the SHARED read-only detail body (hero, info sections, wide
// "Details List" table with per-line History popover, per-line department review matrix,
// header history). Extracted verbatim from ViewRequest/Show (2026-07-22) when the Close
// screen needed the identical detail — one component, so the screens can't drift.
//
// Props: complaint (the loadFullDetail() payload) · listRoute/listLabel (breadcrumb + Back)
// · actions (optional node rendered after the info sections — Close puts its three
// action buttons there, matching the legacy page's "Action:" placement).

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 dash = (v) => (v === null || v === undefined || v === '' || v === '—' ? '—' : v)
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 money = (v) => { if (v === null || v === undefined || v === '') return '—'; const n = Number(v); return Number.isFinite(n) ? n.toLocaleString('en-US', { maximumFractionDigits: 4 }) : String(v) }
const withUnit = (v, unit) => { const m = money(v); return unit && m !== '—' ? `${m} / ${unit}` : m }

function Icon({ d }) {
    return (
        <span className={DOC_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="flex flex-col 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 py-2 last:border-b-0">
                    <dt className="m-0 text-[11px] font-medium text-muted-foreground">{key}</dt>
                    <dd className="m-0 min-w-0 wrap-break-word text-xs font-medium text-foreground">{dash(val)}</dd>
                </div>
            ))}
        </dl>
    )
}

const STRONG = 'font-semibold text-foreground'
const TOTAL = 'font-semibold tabular-nums text-foreground'
const NUM = 'tabular-nums'
const META = 'tabular-nums text-muted-foreground'
const MUTED = 'text-muted-foreground'

// One row per product line — the wide "Details List Complaint & Returns" table (legacy parity).
const DETAIL_COLS = [
    ['ID', (l, c) => c.ID, 'font-bold tabular-nums text-foreground'],
    ['Principal Name', (l) => dash(l.PrincipalDisplayName), STRONG],
    ['Product Name', (l) => dash(l.ProductDisplayName), STRONG],
    ['Application', (l) => dash(l.ApplicationName), ''],
    ['Qty Packing', (l) => withUnit(l.QuantityPacking, l.SatuanPackingName), META],
    ['Lot Number', (l) => dash(l.BarangListID), META],
    ['Complain Qty', (l) => withUnit(l.ComplainQuantity, l.SatuanComplainQuantityName), NUM],
    ['Unit Price IDR', (l) => money(l.UnitPriceIDR), NUM],
    ['Total Value IDR', (l) => money(l.TotalValueIDR), TOTAL],
    ['Unit Price USD', (l) => withUnit(l.UnitPriceUSD, l.SatuanUnitPriceUSDName), NUM],
    ['Total Value USD', (l) => money(l.TotalValueUSD), TOTAL],
    ['USD Rate', (l) => money(l.USDRate), META],
    ['SJ No', (l) => dash(l.SJNo), MUTED],
    ['SJ Date', (l) => fmtDate(l.SJDate), META],
    ['Invoice No', (l) => dash(l.InvoiceNo), MUTED],
    ['Invoice Date', (l) => fmtDate(l.InvoiceDate), META],
    ['Bank', (l) => dash(l.BankName), MUTED],
    ['Nama Rekening', (l) => dash(l.BankAccountName), MUTED],
    ['No Rekening', (l) => dash(l.BankAccountNumber), META],
    ['Total Refund', (l) => money(l.TotalRefund), TOTAL],
    ['Is Paid', (l) => (l.IsPaid === null || l.IsPaid === undefined ? '—' : (l.IsPaid ? 'Yes' : 'No')), MUTED],
    ['Paid Date', (l) => fmtDate(l.PaidDate), META],
    ['Complain Desc', (l) => dash(l.ComplainDesc), MUTED],
    ['Customer Expectation', (l) => dash(l.CustomerExpectation), MUTED],
    ['Reporter Request Expectation', (l) => dash(l.ReporterRequestExpectation), MUTED],
]

function lineHistoryEvents(line) {
    return (line.lineHistory ?? []).map((h) => ({
        status: `${h.StatusName ?? ''}${h.DepartmentName ? ` ${h.DepartmentName}` : ''}`.trim() || '—',
        tanggal: fmtDateTime(h.Tanggal),
        user: h.User,
        remark: h.ReviewRemark || h.AssignRemark || h.DoneRemark || h.FeedbackRemark || h.Remark,
    }))
}

export function ComplaintDetailView({ complaint: c, listRoute, listLabel = 'Complain & Returns', title = 'Complaint & Returns Report', actions = null, headerActions = null }) {
    const complaintFields = {
        'Complain Type': dash(c.ComplainTypeName),
        'Complain Reason': dash(c.ComplainReasonName),
        'Complain Date': fmtDate(c.ComplainDate),
        'Input Date': fmtDateTime(c.InputDate),
        File: <AttachmentLink name={c.UploadName} url={c.FileUrl} />,
    }
    const companyFields = {
        Company: dash(c.CompanyName),
        'Company Address': dash(c.CompanyAddress),
        'Company Telephone': dash(c.Telp),
        'Contact Person': dash(c.CompanyCPName),
        Division: dash(c.DivisionName),
        Creator: dash(c.Creator),
        Sales: dash(c.Sales),
    }

    return (
        <section className="flex min-w-0 flex-col gap-4.5">
            <header className="flex items-center justify-between gap-4">
                <p className="m-0 flex items-center gap-2 text-xs font-semibold text-muted-foreground">
                    <Link href={route(listRoute)} className="text-muted-foreground no-underline hover:text-primary">{listLabel}</Link>
                    <span aria-hidden="true">›</span>
                    <span className="text-foreground">{title}</span>
                </p>
                <div className="flex shrink-0 items-center gap-2">
                    {/* Header-level history = the clock chip (design-system rule) — not a page-bottom table */}
                    <HistoryTimelinePopover entries={(c.headerHistory ?? []).map((h) => ({ Status: h.StatusName, Tanggal: fmtDateTime(h.Tanggal), User: h.User, Comment: h.Comment }))} />
                    <Link href={route(listRoute)} className={BACK_BTN}>
                        <ArrowLeft className="size-3.5" />
                        Back to List
                    </Link>
                </div>
            </header>

            {/* Hero */}
            <article className="flex flex-wrap items-center justify-between gap-4 rounded-2xl border border-border bg-card p-[18px_22px] shadow-sm">
                <div className="flex min-w-0 items-center gap-3.5">
                    <span className="inline-grid size-11.5 shrink-0 place-items-center rounded-xl bg-accent text-primary" aria-hidden="true">
                        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                            <path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z" /><line x1="12" y1="9" x2="12" y2="13" /><line x1="12" y1="17" x2="12.01" y2="17" />
                        </svg>
                    </span>
                    <div className="min-w-0">
                        <h1 className="m-0 text-[22px] font-extrabold leading-[1.2] text-foreground">{title}</h1>
                        <small className="flex flex-wrap items-center gap-2 text-xs font-medium text-muted-foreground">
                            {c.ComplainTypeName && <StatusBadge tone={complaintTypeTone(c.ComplainTypeName)}>{c.ComplainTypeName}{c.ComplainReasonName ? ` (${c.ComplainReasonName})` : ''}</StatusBadge>}
                            {c.StatusName && <StatusBadge tone={complaintStatusTone(c.StatusName)}>{c.StatusName}</StatusBadge>}
                            <span>Report #{c.ID} · {c.CompanyName}</span>
                        </small>
                    </div>
                </div>

                {/* Page-level actions (Change Status / Print / Cancel), matching the Quotation
                    detail's hero cluster. These are NOT decisions against the record — the
                    Close screen's Close / Back-to-Review / Back-to-CEO stay in the pinned
                    DecisionBar pill, per .claude/rules/ui-conventions.md. */}
                {headerActions && (
                    <div className="flex flex-wrap items-center gap-2">
                        {headerActions}
                    </div>
                )}
            </article>

            {c.commercialColumnsHidden && (
                <div className="rounded-xl border border-warning/40 bg-warning/10 px-4 py-2.5 text-xs font-semibold text-warning-text">
                    Commercial data (prices, invoice, bank, refund) is hidden for your department.
                </div>
            )}

            {/* Info sections */}
            <article className="rounded-2xl border border-border bg-card p-[22px_24px] shadow-sm">
                <div className="grid grid-cols-2 gap-3.5 max-[860px]:grid-cols-1">
                    <section className={DOC_SECTION}>
                        <h3 className={DOC_HEADING}><Icon 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}><Icon 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>
            </article>

            {/* Screen-specific actions (e.g. Close / Back to Review / Back to Approval CEO) */}
            {actions}

            {/* Details List — wide table, one row per line */}
            <article className="rounded-2xl border border-border bg-card shadow-sm">
                <header className="flex items-center gap-2.5 border-b border-border p-[18px_22px]">
                    <Icon d={<><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" /></>} />
                    <div>
                        <h2 className="m-0 text-sm font-extrabold leading-[1.2] text-foreground">Details List Complaint &amp; Returns</h2>
                        <small className="block text-[11px] font-medium text-muted-foreground">Product line breakdown</small>
                    </div>
                </header>
                <div className="overflow-x-auto">
                    <table className="w-full min-w-[1600px] border-collapse [&_tbody_td]:border-b [&_tbody_td]:border-border/50 [&_tbody_td]:whitespace-nowrap [&_tbody_td]:px-3.5 [&_tbody_td]:py-3 [&_tbody_td]:align-middle [&_tbody_td]:text-[12px] [&_tbody_td]:text-foreground [&_tbody_tr:last-child_td]:border-b-0 [&_tbody_tr:hover_td]:bg-secondary/60 [&_thead_th]:whitespace-nowrap [&_thead_th]:border-b [&_thead_th]:border-border [&_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 [&_thead_th:first-child]:pl-5 [&_tbody_td:first-child]:pl-5 [&_thead_th:last-child]:pr-5 [&_tbody_td:last-child]:pr-5">
                        <thead>
                            <tr>
                                {DETAIL_COLS.map(([label]) => <th key={label}>{label}</th>)}
                                <th className="!text-center">History</th>
                            </tr>
                        </thead>
                        <tbody>
                            {c.lines.map((line) => (
                                <tr key={line.ID}>
                                    {DETAIL_COLS.map(([label, get, cls]) => (
                                        <td key={label} className={cls}>{get(line, c)}</td>
                                    ))}
                                    <td className="text-center">
                                        <HistoryPopover count={line.lineHistory?.length ?? 0} title="History">
                                            {lineHistoryEvents(line).map((e, n) => (
                                                <div key={n} className="flex flex-col gap-0.5 border-b border-border/50 pb-1.5 last:border-b-0">
                                                    <div className="flex items-center justify-between gap-2">
                                                        <StatusBadge tone={complaintStatusTone(e.status)}>{e.status}</StatusBadge>
                                                        <span className="shrink-0 text-[10px] font-medium tabular-nums text-muted-foreground">{e.tanggal}</span>
                                                    </div>
                                                    {e.user && <span className="text-[11px] font-semibold text-foreground">{e.user}</span>}
                                                    {e.remark && <span className="text-[11px] text-muted-foreground">{e.remark}</span>}
                                                </div>
                                            ))}
                                        </HistoryPopover>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            </article>

            {/* Per-line department review matrix (kept beyond the proto — user decision) */}
            {c.lines.map((line, idx) => (
                <article key={line.ID} className="rounded-2xl border border-border bg-card p-[18px_22px] shadow-sm">
                    <h3 className="m-0 mb-3 flex flex-wrap items-center gap-2 text-xs font-bold uppercase tracking-wide text-muted-foreground">
                        Department Review Matrix — Line {idx + 1}
                        <span className="font-semibold normal-case tracking-normal text-foreground">{line.ProductDisplayName}</span>
                        {line.ComplainDetailsStatusName && <StatusBadge tone={complaintStatusTone(line.ComplainDetailsStatusName)}>{line.ComplainDetailsStatusName}</StatusBadge>}
                    </h3>
                    <div className="overflow-x-auto rounded-xl border border-border/60">
                        <table className="w-full min-w-[720px] text-[12px]">
                            <thead>
                                <tr className="bg-muted/40 text-left text-[11px] font-semibold uppercase tracking-wide text-muted-foreground border-b border-border/70">
                                    <th className="px-3 py-2">Department</th><th className="px-3 py-2">Status</th>
                                    <th className="px-3 py-2">Review</th><th className="px-3 py-2">Assign</th>
                                    <th className="px-3 py-2">Done</th><th className="px-3 py-2">Feedback</th>
                                </tr>
                            </thead>
                            <tbody>
                                {(line.actions ?? []).map((a) => (
                                    <tr key={a.ID} className="border-b border-border/40 hover:bg-muted/30 transition-colors">
                                        <td className="px-3 py-2 font-semibold text-text-heading">{a.DepartmentName}</td>
                                        <td className="px-3 py-2">{a.StatusName ? <StatusBadge tone={complaintStatusTone(a.StatusName)}>{a.StatusName}</StatusBadge> : '—'}</td>
                                        <td className="px-3 py-2 text-muted-foreground">{a.ReviewRemark || '—'}</td>
                                        <td className="px-3 py-2 text-muted-foreground">{a.AssignRemark || '—'}</td>
                                        <td className="px-3 py-2 text-muted-foreground">{a.DoneRemark || '—'}</td>
                                        <td className="px-3 py-2 text-muted-foreground">{a.FeedbackRemark || '—'}</td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                </article>
            ))}

        </section>
    )
}
