"use client"

import { useState } from "react"
import { Download } from "lucide-react"

import { reportsApi } from "@/lib/api/general-ledger"
import { errorMessage } from "@/lib/error-map"
import { ReportType } from "@/types/general-ledger"

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

interface DownloadPdfButtonProps {
  reportType: ReportType
  /** Same filter params already sent to the Json call — outputFormat is added here, not by the caller. */
  params: Record<string, string | number | undefined>
  /** Disable while the on-screen report itself hasn't loaded (nothing to name the download after would be odd otherwise). */
  disabled?: boolean
}

export function DownloadPdfButton({ reportType, params, disabled }: DownloadPdfButtonProps) {
  const [downloading, setDownloading] = useState(false)

  async function handleDownload() {
    setDownloading(true)
    try {
      await reportsApi.downloadPdf(reportType, params)
    } catch (err) {
      toast.error("Could not download report", errorMessage(err))
    } finally {
      setDownloading(false)
    }
  }

  return (
    <Button variant="outline" onClick={handleDownload} disabled={disabled || downloading}>
      <Download className="size-4" />
      {downloading ? "Preparing…" : "Download PDF"}
    </Button>
  )
}
