// General Affairs — "Print Request" button (Phase 6, 2026-07-24).
// Generates the Vehicle Service Request report CLIENT-SIDE from the detail page's existing props
// (no server round-trip). react-pdf is lazy-imported INSIDE the click handler so it never enters
// the main bundle / SSR (CLAUDE.md PDF rule). Drop into any GA detail header.
import { useState } from 'react';
import { usePage } from '@inertiajs/react';
import { Loader2, Printer } from 'lucide-react';
import { useToast } from '@/Components/Toast';

const 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 disabled:opacity-60';

export function PrintReportButton({ request, lines = [], history = [], className = '' }) {
    const { show: showToast } = useToast();
    const user = usePage().props?.auth?.user;
    const [busy, setBusy] = useState(false);

    const print = async () => {
        setBusy(true);
        // Pre-open the tab synchronously so pop-up blockers allow it (the blob URL fills it in).
        const win = window.open('', '_blank');
        try {
            const [{ pdf }, { VehicleServiceRequestReportPdf }] = await Promise.all([
                import('@react-pdf/renderer'),
                import('@/Components/MenuGeneralAffairs/pdf/VehicleServiceRequestReportPdf'),
            ]);
            const now = new Date();
            const stamp = now.toISOString().slice(0, 16).replace('T', ' ');
            const blob = await pdf(
                <VehicleServiceRequestReportPdf
                    request={request}
                    lines={lines}
                    history={history}
                    generatedBy={user?.Nama ?? ''}
                    generatedAt={stamp}
                />,
            ).toBlob();
            const url = URL.createObjectURL(blob);
            if (win) win.location.href = url;
            else window.open(url, '_blank');
        } catch (e) {
            if (win) win.close();
            showToast('Could not generate the report — please try again.', 'error');
        } finally {
            setBusy(false);
        }
    };

    return (
        <button type="button" onClick={print} disabled={busy} className={`${BTN} ${className}`}>
            {busy ? <Loader2 className="size-3.5 animate-spin" /> : <Printer className="size-3.5" />}
            Print Request
        </button>
    );
}

export default PrintReportButton;
