"use client";

import { useState } from "react";
import { FileSpreadsheet, FileText } from "lucide-react";
import { Button } from "@/components/ui/button";
import type { ReportColumn } from "@/lib/types";

type Row = Record<string, unknown>;

/**
 * Excel + PDF export for any tabular report. Libraries (xlsx, @react-pdf/renderer)
 * are dynamically imported so they don't bloat the initial bundle.
 */
export function ExportButtons({
  title,
  columns,
  rows,
}: {
  title: string;
  columns: ReportColumn[];
  rows: Row[];
}) {
  const [busy, setBusy] = useState<"excel" | "pdf" | null>(null);

  function cell(row: Row, key: string): string {
    const v = row[key];
    if (v === null || v === undefined) return "";
    return String(v);
  }

  async function exportExcel() {
    setBusy("excel");
    try {
      const XLSX = await import("xlsx");
      const aoa = [
        columns.map((c) => c.label),
        ...rows.map((r) => columns.map((c) => cell(r, c.key))),
      ];
      const ws = XLSX.utils.aoa_to_sheet(aoa);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "Report");
      XLSX.writeFile(wb, `${slug(title)}.xlsx`);
    } finally {
      setBusy(null);
    }
  }

  async function exportPdf() {
    setBusy("pdf");
    try {
      const { pdf, Document, Page, View, Text, StyleSheet } = await import(
        "@react-pdf/renderer"
      );
      const s = StyleSheet.create({
        page: { padding: 24, fontSize: 8 },
        h1: { fontSize: 14, marginBottom: 12, fontWeight: "bold" },
        row: { flexDirection: "row", borderBottomWidth: 0.5, borderColor: "#ccc" },
        header: { flexDirection: "row", backgroundColor: "#1A2B5C", color: "#fff" },
        cell: { flex: 1, padding: 4 },
      });
      const doc = (
        <Document>
          <Page size="A4" orientation="landscape" style={s.page}>
            <Text style={s.h1}>{title}</Text>
            <View style={s.header}>
              {columns.map((c) => (
                <Text key={c.key} style={s.cell}>
                  {c.label}
                </Text>
              ))}
            </View>
            {rows.map((r, i) => (
              <View key={i} style={s.row}>
                {columns.map((c) => (
                  <Text key={c.key} style={s.cell}>
                    {cell(r, c.key)}
                  </Text>
                ))}
              </View>
            ))}
          </Page>
        </Document>
      );
      const blob = await pdf(doc).toBlob();
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `${slug(title)}.pdf`;
      a.click();
      URL.revokeObjectURL(url);
    } finally {
      setBusy(null);
    }
  }

  return (
    <div className="flex gap-2">
      <Button variant="outline" size="sm" onClick={exportExcel} disabled={busy !== null}>
        <FileSpreadsheet className="size-4" />
        {busy === "excel" ? "Exporting…" : "Excel"}
      </Button>
      <Button variant="outline" size="sm" onClick={exportPdf} disabled={busy !== null}>
        <FileText className="size-4" />
        {busy === "pdf" ? "Exporting…" : "PDF"}
      </Button>
    </div>
  );
}

function slug(s: string) {
  return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
}
