"use client";

import * as React from "react";
import { Download } from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";

interface PdfDownloadButtonProps {
  endpoint: string;
  filename: string;
  variant?: "default" | "outline";
  size?: "default" | "sm";
}

export function PdfDownloadButton({
  endpoint,
  filename,
  variant = "default",
  size = "default",
}: PdfDownloadButtonProps) {
  const [isLoading, startTransition] = React.useTransition();

  const onDownload = () => {
    startTransition(async () => {
      try {
        const response = await fetch(endpoint, {
          method: "GET",
        });

        if (!response.ok) {
          throw new Error("Failed to generate PDF.");
        }

        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = url;
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        link.remove();
        window.URL.revokeObjectURL(url);
      } catch (error) {
        const message =
          error instanceof Error ? error.message : "Unable to download PDF.";
        toast.error(message);
      }
    });
  };

  return (
    <Button variant={variant} size={size} onClick={onDownload} disabled={isLoading}>
      <Download className="size-4" />
      {isLoading ? "Generating PDF..." : "Download PDF"}
    </Button>
  );
}
