'use client';

/**
 * Branded "Export" → a one-page board-report PDF of the current Sentinel
 * snapshot (jsPDF + autotable, both already in the repo). Header carries the
 * Evidence Action ink/magenta brand; body summarizes the headline KPIs and the
 * top issues. Kept intentionally simple — a snapshot, not a full report.
 */
import { useCallback, useState } from 'react';
import type { SentinelData } from '@/lib/executive/types';

const INK: [number, number, number] = [32, 37, 58];
const MAGENTA: [number, number, number] = [230, 0, 160];

export function useExecutiveExport() {
    const [exporting, setExporting] = useState(false);

    const exportPdf = useCallback(async (data: SentinelData) => {
        setExporting(true);
        try {
            const { jsPDF } = await import('jspdf');
            const autoTable = (await import('jspdf-autotable')).default;
            const doc = new jsPDF({ orientation: 'portrait', unit: 'pt', format: 'a4' });
            const W = doc.internal.pageSize.getWidth();

            // Brand header band
            doc.setFillColor(...INK);
            doc.rect(0, 0, W, 70, 'F');
            doc.setFillColor(...MAGENTA);
            doc.rect(40, 26, 6, 20, 'F'); // the slash
            doc.setTextColor(255, 255, 255);
            doc.setFont('helvetica', 'bold');
            doc.setFontSize(16);
            doc.text('UpTime Sentinel — Executive Report', 56, 42);
            doc.setFont('helvetica', 'normal');
            doc.setFontSize(9);
            doc.text(`Generated ${new Date(data.lastUpdated).toUTCString()}`, 56, 56);

            const o = data.overview;
            autoTable(doc, {
                startY: 92,
                head: [['Metric', 'Value', 'Δ vs last month']],
                body: [
                    ['Platform uptime', `${o.overallUptime.toFixed(2)}%`, `${o.uptimeTrend >= 0 ? '+' : ''}${o.uptimeTrend}%`],
                    ['Active incidents', String(o.activeIncidents), `${o.incidentsTrend}%`],
                    ['Avg response', `${o.avgResponseTime} ms`, `${o.responseTrend}%`],
                    ['Monitors up', `${o.activeMonitors}/${o.totalMonitors}`, '—'],
                    ['Response p50 / p95 / p99', `${data.responsePercentiles.p50} / ${data.responsePercentiles.p95} / ${data.responsePercentiles.p99} ms`, '—'],
                ],
                theme: 'grid',
                headStyles: { fillColor: INK, textColor: 255, fontStyle: 'bold' },
                styles: { font: 'helvetica', fontSize: 10, cellPadding: 6 },
            });

            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            const afterKpis = (doc as any).lastAutoTable?.finalY ?? 240;
            doc.setTextColor(...INK);
            doc.setFont('helvetica', 'bold');
            doc.setFontSize(12);
            doc.text('Top issues — last 30 days', 40, afterKpis + 28);
            autoTable(doc, {
                startY: afterKpis + 38,
                head: [['Monitor', 'Type', 'Incidents', 'Downtime (min)']],
                body: data.topIssues.map((t) => [t.name, t.type, String(t.incidents), String(t.downtime)]),
                theme: 'striped',
                headStyles: { fillColor: MAGENTA, textColor: 255, fontStyle: 'bold' },
                styles: { font: 'helvetica', fontSize: 10, cellPadding: 6 },
            });

            doc.save(`uptime-sentinel-${data.lastUpdated.slice(0, 10)}.pdf`);
        } finally {
            setExporting(false);
        }
    }, []);

    return { exportPdf, exporting };
}
