import { Link, useForm } from '@inertiajs/react'
import { ArrowLeft, Loader2, MessageSquare, Send } from 'lucide-react'
import AppLayout from '@/Layouts/AppLayout'
import { Button } from '@/Components/ui/button'
import { StatusBadge } from '@/Components/Proto/UI/StatusBadge'
import { useToast } from '@/Components/Toast'
import { complaintTypeTone } from '@/lib/complaintTone'
import { HistoryTimelinePopover } from '@/Components/MenuQuotations/QuotationDetailPage/HistoryTimelinePopover'
import { DecisionBar } from '@/Components/MenuSampleOrders/DecisionBar'
import { AttachmentLink } from '@/Components/MenuComplaintAndReturns/AttachmentLink'

// Complaint & Returns — Review detail + action (all six departments share this page). Faithful
// port of the proto Proto/Complaints/ReviewPmDetail.jsx (README rule 10): warning-icon hero, the
// six-section read-only doc grid, an editable Remark, the two-button submit and the history table.
// Data + submit wiring are REAL and unchanged (PRD §6.1 / Q13): "Submit Review" finalizes the
// department's review (may promote complaint-wide); "Submit Remark Only" saves a draft remark with
// no status change.

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

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">{val}</dd>
                </div>
            ))}
        </dl>
    )
}

export default function Show({ dept, deptName, line, history }) {
    const { show: showToast } = useToast()
    const form = useForm({ remark: line.ReviewRemark ?? '', submit: 'review' })

    const submitAs = (submit) => (e) => {
        e.preventDefault()
        form.transform((data) => ({ ...data, submit }))
        form.post(route('complaints.review.act', [dept, line.ID]), {
            onError: () => showToast('Please check the form and try again.', 'error'),
        })
    }

    const complaintFields = {
        'Complain Type': dash(line.ComplainTypeName),
        'Complain Reason': dash(line.ComplainReasonName),
        'Complain Date': fmtDate(line.ComplainDate),
        File: <AttachmentLink name={line.FileName} url={line.FileUrl} />,
    }
    const companyFields = {
        Company: dash(line.CompanyName),
        'Company Address': dash(line.CompanyAddress),
        'Company Telephone': dash(line.CompanyTelp),
        Division: dash(line.DivisionName),
        Sales: dash(line.Sales),
        Creator: dash(line.Creator),
    }
    const productFields = {
        Principal: dash(line.PrincipalName),
        'Product Name': dash(line.ProductName),
        Application: dash(line.ApplicationName),
        Packing: withUnit(line.QuantityPacking, line.PackingUnitName),
        'Complaint Quantity': withUnit(line.ComplainQuantity, line.ComplainUnitName),
        'Lot Number': dash(line.BarangListID),
    }
    const pricingFields = {
        'USD Rate': num(line.USDRate),
        'Unit Price $': withUnit(line.UnitPriceUSD, line.PriceUnitName),
        'Unit Price IDR': num(line.UnitPriceIDR),
        'Total Value USD': num(line.TotalValueUSD),
        'Total Value IDR': num(line.TotalValueIDR),
    }
    const shippingFields = {
        'SJ No': dash(line.SJNo),
        'SJ Date': fmtDate(line.SJDate),
        'Invoice No': dash(line.InvoiceNo),
        'Invoice Date': fmtDate(line.InvoiceDate),
        Paid: line.IsPaid ? 'Is Paid' : 'No',
        'Paid Date': fmtDate(line.PaidDate),
    }
    const refundFields = {
        Bank: dash(line.BankName),
        'Nama Rekening': dash(line.BankAccountName),
        'No Rekening': dash(line.BankAccountNumber),
        'Total Refund': num(line.TotalRefund),
    }
    const expectationFields = {
        'Complain Desc': dash(line.ComplainDesc),
        'Customer Expectation': dash(line.CustomerExpectation),
        'Reporter Request Expectation': dash(line.ReporterRequestExpectation),
    }
    const isRefund = /refund/i.test(line.ComplainTypeName || '')
    // Logistic sees no money: Pricing & Value and Refund Information are both withheld. The
    // server already strips those keys from `line` (Concerns\RedactsComplainMoney) — this guard
    // is the second layer, so a redacted payload renders no card rather than a card of dashes.
    // Shipping & Invoice, including Paid / Paid Date, stays visible by design.
    const showMoney = dept !== 'logistic'

    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('complaints.review.index', dept)} className="text-muted-foreground no-underline hover:text-primary">Review {deptName}</Link>
                    <span aria-hidden="true">›</span>
                    <span className="text-foreground">Review Complaint &amp; Returns Report</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={(history ?? []).map((h) => ({
                        Status: `${h.Status ?? ''}${h.DepartmentName ? ` ${h.DepartmentName}` : ''}`.trim(),
                        Tanggal: fmtDateTime(h.Tanggal), User: h.User, Comment: h.Remark,
                    }))} />
                    <Link href={route('complaints.review.index', dept)} 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-card-foreground">Review Complaint &amp; Returns Report - {deptName}</h1>
                        <small className="flex flex-wrap items-center gap-2 text-xs font-medium text-muted-foreground">
                            {line.ComplainTypeName && <StatusBadge tone={complaintTypeTone(line.ComplainTypeName)}>{line.ComplainTypeName}</StatusBadge>}
                            <span>Report #{line.ComplainID} · Created on {fmtDateTime(line.InputDate)}</span>
                        </small>
                    </div>
                </div>
            </article>

            {/* Doc sections */}
            <article className="rounded-2xl border border-border bg-card p-[22px_24px] shadow-sm">
                <div className="grid grid-cols-3 gap-3.5 max-[1180px]:grid-cols-2 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>
                    <section className={DOC_SECTION}>
                        <h3 className={DOC_HEADING}><Icon d={<><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" /><polyline points="3.27 6.96 12 12.01 20.73 6.96" /><line x1="12" y1="22.08" x2="12" y2="12" /></>} />Product Details</h3>
                        <DocList fields={productFields} />
                    </section>
                    {showMoney && (
                        <section className={DOC_SECTION}>
                            <h3 className={DOC_HEADING}><Icon d={<><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" /></>} />Pricing &amp; Value</h3>
                            <DocList fields={pricingFields} />
                        </section>
                    )}
                    <section className={DOC_SECTION}>
                        <h3 className={DOC_HEADING}><Icon d={<><rect x="1" y="3" width="15" height="13" rx="1" /><path d="M16 8h4l3 3v5h-7z" /><circle cx="5.5" cy="18.5" r="2.5" /><circle cx="18.5" cy="18.5" r="2.5" /></>} />Shipping &amp; Invoice</h3>
                        <DocList fields={shippingFields} />
                    </section>
                    {isRefund && showMoney && (
                        <section className={DOC_SECTION}>
                            <h3 className={DOC_HEADING}><Icon d={<><rect x="2" y="5" width="20" height="14" rx="2" /><line x1="2" y1="10" x2="22" y2="10" /><path d="M6 15h.01" /><path d="M11 15h2" /></>} />Refund Information</h3>
                            <DocList fields={refundFields} />
                        </section>
                    )}
                    <section className={DOC_SECTION}>
                        <h3 className={DOC_HEADING}><Icon d={<><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" /></>} />Expectation &amp; Remark</h3>
                        <DocList fields={expectationFields} />
                        <div className="mt-3">
                            <label htmlFor="reviewRemark" className="mb-1.5 block text-[11px] font-medium text-muted-foreground">Remark *</label>
                            <textarea id="reviewRemark" rows={3} value={form.data.remark} onChange={(e) => form.setData('remark', e.target.value)} placeholder="Insert Remark"
                                className="w-full resize-y rounded-lg border border-input bg-card px-3 py-2.5 text-xs text-foreground outline-none transition-colors placeholder:text-muted-foreground/55 focus:border-primary focus:ring-1 focus:ring-primary" />
                            {form.errors.remark && <p className="mt-1 text-[11px] font-semibold text-destructive">{form.errors.remark}</p>}
                        </div>
                    </section>
                </div>
            </article>

            {/* Submit actions — floating centre pill (design-system decision bar). The required
                Remark lives in the "Expectation & Remark" card above; only the buttons dock here. */}
            <DecisionBar>
                <span className="hidden text-[12px] font-medium text-muted-foreground sm:inline">Review {deptName} · Report #{line.ComplainID}</span>
                <span className="hidden h-6 w-px bg-border sm:block" />
                <div className="flex w-full items-center gap-2 sm:w-auto sm:gap-2.5">
                    <Button type="button" disabled={form.processing || !form.data.remark} onClick={submitAs('review')} className="h-9 flex-1 gap-1.5 rounded-lg px-4 text-xs font-bold shadow-sm sm:flex-none">
                        {form.processing ? <Loader2 className="size-3.5 animate-spin" /> : <Send className="size-3.5" />} Submit Review
                    </Button>
                    <Button type="button" variant="outline" disabled={form.processing || !form.data.remark} onClick={submitAs('remark_only')} className="h-9 flex-1 gap-1.5 rounded-lg px-4 text-xs font-bold sm:flex-none">
                        <MessageSquare className="size-3.5" /> Submit Remark Only
                    </Button>
                </div>
            </DecisionBar>

        </section>
    )
}

Show.layout = [AppLayout]
