import { useState } from 'react';
import { Link, useHttp, usePage } from '@inertiajs/react';
import { ArrowLeft, Clock, FileSpreadsheet, FileText, Loader2, Package, Printer, RotateCcw } from 'lucide-react';
import AppLayout from '@/Layouts/AppLayout';
import { StatusBadge } from '@/Components/Proto/UI/StatusBadge';
import { DOC_SECTION, DocList, SectionHeading } from '@/Components/MenuSampleOrders/SampleImport/detail/DetailGrammar';
import { LineItemsTable } from '@/Components/MenuSampleOrders/SampleImport/detail/LineItemsTable';
import { HistoryTable } from '@/Components/MenuSampleOrders/SampleImport/detail/HistoryTable';
import { useToast } from '@/Components/Toast';
import { useSampleImportDocumentPdf } from '@/lib/pdf/useSampleImportDocumentPdf';
import { useExcelExport } from '@/lib/excel/useExcelExport';
import { rowsFromPayload } from '@/lib/excel/specs/sampleImportDocumentSpec';

const BACK_BTN = 'inline-flex h-9 items-center justify-center gap-1.5 rounded-lg border border-input bg-card px-4 text-xs font-bold text-foreground transition-colors hover:border-primary hover:text-primary';
// Print: neutral outline (mirrors the Sample-Order print button). Export: success tint (mirrors ExportButton).
const PRINT_BTN = 'inline-flex h-9 items-center justify-center gap-1.5 rounded-lg border border-input bg-card px-4 text-xs font-bold text-foreground transition-colors hover:border-primary hover:text-primary disabled:cursor-not-allowed disabled:opacity-60';
const EXPORT_BTN = 'inline-flex h-9 items-center justify-center gap-1.5 rounded-lg border border-success/40 bg-success/5 px-4 text-xs font-bold text-success-text transition-colors hover:bg-success/15 disabled:cursor-not-allowed disabled:opacity-60';
// Revise: warning tint (mirrors the Approval PM Revise action). Enabled only for a status-6 request the viewer created.
const REVISE_BTN = 'inline-flex h-9 items-center justify-center gap-1.5 rounded-lg border border-warning/40 bg-warning/5 px-4 text-xs font-bold text-warning-text transition-colors hover:bg-warning/15';
// Non-printable status on view/all: the buttons still render, disabled + red (legacy parity).
const DISABLED_BTN = 'inline-flex h-9 items-center justify-center gap-1.5 rounded-lg border border-danger/40 bg-danger/5 px-4 text-xs font-bold text-danger cursor-not-allowed opacity-70';
const DISABLED_HINT = 'Available once the request is Approved MM / Goods Receipt (or a rejected request you created).';
// Legacy trigger (listsamplerequestimportdetails[all].php): Revise is enabled ONLY when the request was
// sent back by Approval PM/MM (status 6) AND the acting user created it; otherwise a disabled red button.
const REVISE_HINT = 'Available only on a request that Approval PM / MM sent back for revision (that you created).';

// Legacy Print/Export enable-condition (samplerequestimportviewexport.php): header status IN (3,4,5)
// OR (status 9 AND the acting user is the creator). Kept in lockstep with document()'s PRINTABLE.
const PRINTABLE = [3, 4, 5];

export default function BrowseDetail({ view, record }) {
    const listUrl = route('sample-orders.request-import.browse', view.slug);
    const meId = Number(usePage().props.auth?.user?.ID ?? 0);

    // Print + Export live on ONLY the view (creator) + all (head-div) browse detail pages — legacy
    // renders them nowhere else. Within those, enabled per the status condition, else disabled+red.
    const showDocActions = view.slug === 'view' || view.slug === 'all';
    const printable = PRINTABLE.includes(record.statusId)
        || (record.statusId === 9 && record.userIdInput === meId);
    // Revise button rides the same view+all surface. Enabled only when the request is at Revise (status 6)
    // AND the viewer created it — mirrors reviseStore's owner + status-6 gate (a disabled red button else).
    const canRevise = record.statusId === 6 && record.userIdInput === meId;

    const http = useHttp({});
    const pdf = useSampleImportDocumentPdf();
    const excel = useExcelExport();
    const { show } = useToast();
    // The /document fetch runs BEFORE excel.run() flips excel.running, so a bare disabled={excel.running}
    // leaves the button live during the fetch — a double-click would fire two GETs. Track the fetch here.
    const [exporting, setExporting] = useState(false);
    const exportBusy = exporting || excel.running;

    // Export: fetch the one gated /document payload, then hand its (already non-void, ordered) lines
    // to the ExcelJS worker via the `sampleImportDocument` specKey. Only the string key crosses the
    // worker boundary; the spec's column functions map each line to the 8 cells (CLAUDE.md ExcelJS rule).
    const onExport = async () => {
        if (exportBusy) {
            return;
        }
        setExporting(true);
        try {
            const payload = await http.get(route('sample-orders.request-import.document', { view: view.slug, id: record.no }));
            excel.run({
                specKey: 'sampleImportDocument',
                rows: rowsFromPayload(payload),
                onSuccess: (n) => show(`Export selesai — ${Number(n).toLocaleString('en-US')} baris.`, 'success'),
                onError: (message) => show(message, 'error'),
            });
        } catch {
            show('Export gagal. Silakan coba lagi.', 'error');
        } finally {
            // Hand the busy baton to excel.running: once run() has kicked off the worker it owns the
            // spinner; if the fetch threw, this simply re-enables the button.
            setExporting(false);
        }
    };

    const headerLeft = {
        'No': <span className="font-bold tabular-nums text-primary">{record.no}</span>,
        'Principal': record.principal,
        'Creator': record.creator,
        'Status': <StatusBadge tone="primary">{record.status}</StatusBadge>,
        'Request From': record.requestFrom,
        'Tanggal': <span className="tabular-nums">{record.tanggal}</span>,
    };
    const headerRight = {
        'Delivery': record.delivery,
        'Urgency': record.urgency ? <StatusBadge tone="neutral">{record.urgency}</StatusBadge> : '',
        'Attention': record.attention,
        'Address': record.address,
        'ETD / ETA': <span className="tabular-nums">{record.etd ?? '—'} / {record.eta ?? '—'}</span>,
        'Comment': record.comment,
    };

    return (
        <section className="flex min-w-0 flex-col gap-5">
            <header>
                <p className="m-0 mb-1.5 flex items-center gap-2 text-xs font-semibold text-muted-foreground">
                    <Link href={listUrl} className="no-underline hover:text-primary">{view.title} — Sample Request Import</Link>
                    <span aria-hidden="true">›</span>
                    <span className="text-foreground">Detail</span>
                </p>
                <div className="flex flex-col items-start gap-3 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
                    <div className="flex min-w-0 flex-col gap-1">
                        <div className="flex items-center gap-3">
                            <h1 className="m-0 text-2xl font-extrabold tracking-tight text-foreground">Sample Request Import #{record.no}</h1>
                            <StatusBadge tone="primary">{record.status}</StatusBadge>
                        </div>
                        <p className="m-0 text-[13px] font-medium text-muted-foreground">{record.principal}</p>
                    </div>
                    <div className="flex flex-wrap items-center gap-2">
                        {showDocActions && (printable ? (
                            <>
                                <button type="button" onClick={() => pdf.print(view.slug, record.no)} disabled={pdf.printing} aria-busy={pdf.printing} className={PRINT_BTN}>
                                    {pdf.printing ? <Loader2 aria-hidden="true" className="size-3.5 animate-spin" /> : <Printer aria-hidden="true" className="size-3.5" />}
                                    Print
                                </button>
                                <button type="button" onClick={onExport} disabled={exportBusy} aria-busy={exportBusy} className={EXPORT_BTN}>
                                    {exportBusy ? <Loader2 aria-hidden="true" className="size-3.5 animate-spin" /> : <FileSpreadsheet aria-hidden="true" className="size-3.5" />}
                                    {excel.running ? `Exporting… ${excel.done}/${excel.total}` : (exporting ? 'Exporting…' : 'Export')}
                                </button>
                            </>
                        ) : (
                            <>
                                <button type="button" disabled aria-disabled="true" title={DISABLED_HINT} className={DISABLED_BTN}>
                                    <Printer aria-hidden="true" className="size-3.5" />Print
                                </button>
                                <button type="button" disabled aria-disabled="true" title={DISABLED_HINT} className={DISABLED_BTN}>
                                    <FileSpreadsheet aria-hidden="true" className="size-3.5" />Export
                                </button>
                            </>
                        ))}
                        {showDocActions && (canRevise ? (
                            <Link href={route('sample-orders.request-import.revise', record.no)} className={REVISE_BTN}>
                                <RotateCcw aria-hidden="true" className="size-3.5" strokeWidth={2.5} />Revise
                            </Link>
                        ) : (
                            <button type="button" disabled aria-disabled="true" title={REVISE_HINT} className={DISABLED_BTN}>
                                <RotateCcw aria-hidden="true" className="size-3.5" strokeWidth={2.5} />Revise
                            </button>
                        ))}
                        <Link href={listUrl} className={BACK_BTN}><ArrowLeft className="size-3.5" />Back to List</Link>
                    </div>
                </div>
            </header>

            <section className={DOC_SECTION}>
                <SectionHeading icon={<FileText className="size-3" />} title="Sample Request Import" />
                <div className="grid grid-cols-2 gap-x-10 pt-1 max-[760px]:grid-cols-1 max-[760px]:gap-x-0">
                    <DocList fields={headerLeft} />
                    <DocList fields={headerRight} />
                </div>
            </section>

            <section className={DOC_SECTION}>
                <SectionHeading icon={<Package className="size-3" />} title="Details List Sample Request Import" pill={record.lines.length} />
                <LineItemsTable lines={record.lines} />
            </section>

            <section className={DOC_SECTION}>
                <SectionHeading icon={<Clock className="size-3" />} title="History Sample Request Import" pill={record.history.length} />
                <HistoryTable history={record.history} />
            </section>
        </section>
    );
}

BrowseDetail.layout = [AppLayout];
