import { Fragment, useState } from 'react';
import { Link, useForm } from '@inertiajs/react';
import { ArrowLeft, Loader2, Send, X } from 'lucide-react';
import AppLayout from '@/Layouts/AppLayout';
import { Button } from '@/Components/ui/button';
import { Switch } from '@/Components/ui/switch';
import { useToast } from '@/Components/Toast';
import { StatusBadge } from '@/Components/Proto/UI/StatusBadge';
import { HistoryTimelinePopover } from '@/Components/MenuQuotations/QuotationDetailPage/HistoryTimelinePopover';
import { DecisionBar } from '@/Components/MenuSampleOrders/DecisionBar';
import { complaintStatusTone, complaintTypeTone } from '@/Proto/complaintsData';

const PRIMARY_BTN = 'inline-flex h-9 items-center justify-center gap-1.5 rounded-lg bg-linear-to-br from-violet-500 to-primary px-4.5 text-xs font-bold text-white shadow-sm transition-[filter] hover:brightness-105 disabled:opacity-60';
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 CARD = 'rounded-2xl border border-border bg-card shadow-sm';
const RING_ICON = 'inline-grid size-6 shrink-0 place-items-center rounded-full border border-primary/50 bg-transparent text-primary';

// NO blanket [&_tbody_td]:font-normal here. An arbitrary variant compiles to a
// DESCENDANT selector (.[&_tbody_td]:font-normal tbody td, specificity 0-2-1), which
// outranks every plain .font-bold / .font-semibold a <td> sets on itself (0-1-0). With
// it, all 25-odd per-cell weights in this file were dead code and the table rendered
// one flat weight — reported 2026-08-24. A <td> is font-normal by default anyway, so
// dropping it changes nothing except letting the cells speak. Same trap applies to
// colour: never add [&_tbody_td]:text-* back unless no cell sets its own.
// Table type matches the app majority — header 11px/600, body 12px — the sizes Quotation
// and Company Rebate detail tables use. This file ran 12px/700 headers over 13px body,
// one step up on BOTH, which is what made the page read larger than every screen beside
// it (measured 2026-08-24). Keep the four Complaint Handling detail files identical:
// their TABLE constants are copies, so changing one alone splits four twin screens.
const TABLE = 'w-full border-collapse '
    + '[&_thead_tr]:bg-card [&_thead_th]:whitespace-nowrap [&_thead_th]:border-b [&_thead_th]:border-border [&_thead_th]:px-4 [&_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 [&_th.text-right]:text-right '
    + '[&_tbody_td]:whitespace-nowrap [&_tbody_td]:border-b [&_tbody_td]:border-border/40 [&_tbody_td]:px-4 [&_tbody_td]:py-3 [&_tbody_td]:align-top [&_tbody_td]:text-[12px] [&_tbody_td]:text-foreground '
    + '[&_tbody_tr:last-child_td]:border-b-0 [&_tbody_tr:hover_td]:bg-muted/20';

// All lot columns render read-only (no department edits any of them in the complete stage).
const LOT_BASE = [{ key: 'lotNumber', label: 'Lot No' }];
const LOT_EXTRA = [
    { key: 'poNumber', label: 'PO No' }, { key: 'poQuantity', label: 'PO Qty', align: true },
    { key: 'poDate', label: 'PO Date' }, { key: 'eta', label: 'ETA' },
    { key: 'grNumber', label: 'GR No' }, { key: 'grDate', label: 'GR Date' },
    { key: 'isPayment', label: 'Is Payment' }, { key: 'paymentDate', label: 'Payment Date' },
    { key: 'stdLotNumber', label: 'Std Lot No' },
];
const LOT_TAIL = [
    { key: 'lotQty', label: 'Lot Qty', align: true }, { key: 'lotQtyProblem', label: 'Lot Problem', align: true },
    { key: 'packaging', label: 'Packaging' }, { key: 'expiredDate', label: 'Expiry' },
    { key: 'complainDetails', label: 'Details' }, { key: 'complainExpectation', label: 'Expectation' },
];

const cv = (v) => (v === '' || v === null || v === undefined) ? <span className="text-muted-foreground/40">—</span> : v;
const lotCell = (l, key) => (key === 'isPayment' ? (l.isPayment ? 'Yes' : 'No') : cv(l[key]));

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>
    );
}

export default function CompleteDetail({ dept, report }) {
    const { show: showToast } = useToast();
    const [showLots, setShowLots] = useState(false);
    const [confirmOpen, setConfirmOpen] = useState(false);
    const form = useForm({ CompleteRemark: '' });

    const lotCols = showLots ? [...LOT_BASE, ...LOT_EXTRA, ...LOT_TAIL] : [...LOT_BASE, ...LOT_TAIL];

    const submit = () => {
        form.post(route('complaint-handling.complete.store', { dept: dept.slug, id: report.id }), {
            preserveScroll: true,
            onSuccess: () => setConfirmOpen(false),
            onError: () => showToast('Check the Complete Remark field.', 'error'),
        });
    };

    const infoRows = [
        ['ID', <span className="font-bold tabular-nums text-primary">{report.id}</span>],
        ['Principal Name', <span className="font-semibold text-foreground">{report.principal}</span>],
        ['Complain Type', <StatusBadge tone={complaintTypeTone(report.complainType)}>{report.complainType}</StatusBadge>],
        ['File', report.fileUrl
            ? <a href={report.fileUrl} className="font-semibold text-primary underline underline-offset-2 hover:text-primary-hover">{report.file}</a>
            : <span className="font-semibold text-foreground">No File</span>],
        ['Created Date', report.createdDate],
        ['Status', <StatusBadge tone={complaintStatusTone(report.status)}>{report.status}</StatusBadge>],
        ['Created By', <span className="font-semibold text-foreground">{report.createdBy}</span>],
        ['Creator Role', <span className="font-semibold text-foreground">{report.creatorRole}</span>],
    ];

    return (
        <section className="flex min-w-0 flex-col gap-4.5 pb-20">
            <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('complaint-handling.complete', { dept: dept.slug })} className="text-muted-foreground no-underline hover:text-primary">Complete {dept.name}</Link>
                    <span aria-hidden="true">›</span>
                    <span className="text-foreground">Complete Complaint Handling Report</span>
                </p>
                <div className="flex shrink-0 items-center gap-2">
                    <HistoryTimelinePopover entries={report.history.map((e) => ({
                        Status: e.dept ? `${e.status} ${e.dept}` : e.status,
                        Tanggal: e.tanggal,
                        User: e.user,
                        Comment: e.remark,
                    }))} />
                    <Link href={route('complaint-handling.complete', { dept: dept.slug })} className={BACK_BTN}>
                        <ArrowLeft className="size-3.5" /> Back to List
                    </Link>
                </div>
            </header>

            <article className="flex flex-wrap items-center justify-between gap-4 rounded-2xl border border-border bg-card shadow-sm p-[18px_22px]">
                <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="M22 11.08V12a10 10 0 1 1-5.93-9.14" /><polyline points="22 4 12 14.01 9 11.01" />
                        </svg>
                    </span>
                    <div className="min-w-0">
                        <h1 className="m-0 text-[22px] font-extrabold leading-[1.2] text-card-foreground">Complete Complaint Handling Report - {dept.name}</h1>
                        <small className="flex flex-wrap items-center gap-2 text-xs font-medium text-muted-foreground">
                            <StatusBadge tone={complaintTypeTone(report.complainType)}>{report.complainType}</StatusBadge>
                            <span>Report #{report.id}</span>
                        </small>
                    </div>
                </div>
            </article>

            <article className={CARD}>
                <h3 className="m-0 flex items-center gap-2 border-b border-border p-[16px_20px] text-xs font-bold uppercase tracking-wide text-foreground">
                    <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" /></>} />
                    Report Information
                </h3>
                <dl className="grid grid-cols-2 gap-x-10 p-[6px_20px_14px] max-[640px]:grid-cols-1">
                    {infoRows.map(([label, value]) => (
                        <div key={label} className="grid grid-cols-[minmax(0,140px)_1fr] items-center gap-2.5 border-b border-dashed border-border py-2.5 last:border-b-0">
                            <dt className="m-0 text-xs font-medium text-muted-foreground">{label}</dt>
                            <dd className="m-0 min-w-0 text-[13px] font-semibold text-foreground">{value}</dd>
                        </div>
                    ))}
                </dl>
            </article>

            <article className={CARD}>
                <header className="flex flex-wrap items-center justify-between gap-3 border-b border-border p-[14px_20px]">
                    <div className="flex items-center gap-2 text-xs font-bold uppercase tracking-wide text-foreground">
                        <Ring 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" /></>} />
                        Details
                    </div>
                    <label className="flex cursor-pointer items-center gap-2 text-[12px] font-semibold text-muted-foreground select-none">
                        <Switch checked={showLots} onCheckedChange={setShowLots} /> Show Details Lot
                    </label>
                </header>
                <div className="overflow-x-auto p-3">
                    {/* `w-fit min-w-full` keeps this box from capping at 100% of the scroller —
                        without it `overflow-hidden` clips the lot columns instead of letting the
                        scroller scroll to them. See ReviewDetail.jsx for the measured case. */}
                    <div className="w-fit min-w-full rounded-xl border border-border/60 shadow-2xs overflow-hidden">
                        <table className={TABLE}>
                            <thead>
                                <tr>
                                    <th>Product</th>
                                    <th className="text-right">Total</th>
                                    <th className="text-right">Problem</th>
                                    {lotCols.map((c) => <th key={c.key} className={c.align ? 'text-right' : ''}>{c.label}</th>)}
                                </tr>
                            </thead>
                            <tbody>
                                {report.products.map((p, pi) => p.lots.map((l, li) => (
                                    <tr key={`${pi}-${li}`} className={li === 0 && pi > 0 ? 'border-t border-border' : ''}>
                                        {li === 0 && (
                                            <Fragment>
                                                <td rowSpan={p.lots.length} className="font-bold text-foreground align-top bg-card border-r border-border/40 text-[12px]">{p.product}</td>
                                                <td rowSpan={p.lots.length} className="text-right tabular-nums font-semibold text-foreground align-top bg-card border-r border-border/40 text-[12px]">{p.totalQty}</td>
                                                <td rowSpan={p.lots.length} className="text-right tabular-nums font-semibold text-foreground align-top bg-card border-r border-border/40 text-[12px]">{p.totalQtyProblem}</td>
                                            </Fragment>
                                        )}
                                        {lotCols.map((c) => (
                                            <td key={c.key} className={c.align ? 'text-right tabular-nums font-semibold text-foreground text-[12px]' : (c.key === 'lotNumber' ? 'font-semibold text-foreground text-[12px]' : 'text-foreground font-normal text-[12px]')}>
                                                {lotCell(l, c.key)}
                                            </td>
                                        ))}
                                    </tr>
                                )))}
                            </tbody>
                        </table>
                    </div>
                </div>
            </article>

            <DecisionBar>
                <span className="hidden whitespace-nowrap text-[12.5px] font-semibold text-muted-foreground sm:inline">
                    Complete {dept.name} · Report <span className="font-extrabold text-foreground">#{report.id}</span>
                </span>
                <span className="hidden h-6 w-px bg-border sm:block" aria-hidden="true" />
                <div className="flex flex-wrap items-center gap-2.5">
                    <Button type="button" onClick={() => setConfirmOpen(true)} disabled={form.processing} className={PRIMARY_BTN}>
                        <Send className="size-3.5" /> Complete Complaint Handling
                    </Button>
                </div>
            </DecisionBar>

            {confirmOpen && (
                <div className="fixed inset-0 z-100 grid place-items-center bg-black/40 p-4" role="dialog" aria-modal="true" onClick={() => !form.processing && setConfirmOpen(false)}>
                    <div className={`${CARD} w-full max-w-md`} onClick={(e) => e.stopPropagation()}>
                        <header className="flex items-center gap-2.5 border-b border-border px-5 py-4">
                            <span className={RING_ICON} aria-hidden="true"><Send className="size-3" /></span>
                            <h2 className="m-0 text-sm font-bold text-card-foreground">Complete {dept.name} Assignment — Report #{report.id}</h2>
                            <button type="button" onClick={() => setConfirmOpen(false)} className="ml-auto grid size-7 place-items-center rounded-lg text-muted-foreground hover:bg-secondary hover:text-foreground" aria-label="Close">
                                <X className="size-4" />
                            </button>
                        </header>
                        <div className="px-5 py-4">
                            <label htmlFor="completeRemark" className="mb-1.5 block text-xs font-bold text-foreground">
                                Complete Remark <span className="text-danger">*</span>
                            </label>
                            <textarea id="completeRemark" rows={3} autoFocus value={form.data.CompleteRemark} onChange={(e) => form.setData('CompleteRemark', e.target.value)} placeholder="Tulis catatan complete remark…"
                                className="w-full resize-y rounded-lg border border-input bg-card px-3.5 py-2.5 text-[13px] text-card-foreground outline-none transition-colors focus:border-primary" />
                            {form.errors.CompleteRemark && <p className="mt-1 text-xs text-destructive">{form.errors.CompleteRemark}</p>}
                        </div>
                        <footer className="flex items-center justify-start gap-2.5 border-t border-border px-5 py-3.5">
                            <Button type="button" onClick={submit} disabled={form.processing || !form.data.CompleteRemark.trim()} className={PRIMARY_BTN}>
                                {form.processing ? <><Loader2 className="size-3.5 animate-spin" /> Menyimpan…</> : <><Send className="size-3.5" /> Complete Complaint Handling</>}
                            </Button>
                            <button type="button" onClick={() => setConfirmOpen(false)} disabled={form.processing}
                                className="inline-flex h-9 items-center justify-center rounded-lg border border-input bg-card px-4 text-xs font-bold text-foreground transition-colors hover:border-primary hover:text-primary">Cancel</button>
                        </footer>
                    </div>
                </div>
            )}
        </section>
    );
}

CompleteDetail.layout = [AppLayout];
