import { useState } from 'react'
import { useHttp } from '@inertiajs/react'
import { Loader2, Printer } from 'lucide-react'
import { Button } from '@/Components/ui/button'
import { useToast } from '@/Components/Toast'
import { openReactPdfInNewTab } from '@/lib/pdf/openReactPdf'

// Print Complaint (legacy btn-print). Enabled only at header status {3,4,5,6}; outside that
// window the legacy drew a disabled red "Cannot Print" twin rather than nothing, so this does
// too. Rendered only when capabilities.print — head-dept had its whole Action row commented out.
//
// Legacy's btn-print branch has every INSERT commented out: it opens the report and writes
// nothing. So there is no audit POST here, unlike LWR's print which does record one.
const PRINTABLE_STATUSES = [3, 4, 5, 6]
const PRINT_BTN = 'inline-flex h-9 items-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'
const DANGER_BTN = 'h-9 rounded-lg border border-danger/40 bg-card px-4 text-xs font-bold text-danger-text opacity-60'

// @react-pdf/renderer is loaded lazily inside the handler — a top-level import crashes Inertia
// SSR (Node-only transitive deps resolving `fs`) and drags ~480 KB gzip into the main chunk.
const loadRenderer = () =>
    import('@/Components/MenuComplaintAndReturns/pdf/ComplaintReportPdf').then((m) => m.renderComplaintReportBlob)

export function PrintComplaintButton({ complaintId, statusId }) {
    const http = useHttp({})
    const { show: showToast } = useToast()
    const [busy, setBusy] = useState(false)

    if (!PRINTABLE_STATUSES.includes(Number(statusId))) {
        return (
            <Button type="button" variant="ghost" disabled className={DANGER_BTN}>
                Cannot Print
            </Button>
        )
    }

    const print = () => {
        if (busy) return
        setBusy(true)
        // openReactPdfInNewTab pre-opens the tab synchronously inside this click gesture, so the
        // awaited fetch + render below cannot trip a popup blocker.
        openReactPdfInNewTab(async () => {
            const payload = await http.get(route('complaints.report', complaintId))
            const render = await loadRenderer()

            return render(payload)
        })
            .catch(() => showToast('Gagal membuka PDF. Silakan coba lagi.', 'error'))
            .finally(() => setBusy(false))
    }

    return (
        <Button type="button" variant="ghost" disabled={busy} onClick={print} className={PRINT_BTN}>
            {busy ? <Loader2 className="size-3.5 animate-spin" /> : <Printer className="size-3.5" />}
            Print Complaint
        </Button>
    )
}
