"use client"

import { useState } from "react"
import { FileSpreadsheet } 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 DownloadCsvButtonProps {
  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
}

/** Same mechanism as DownloadPdfButton, `outputFormat=Csv` — GL's bytes are downloaded unmodified. */
export function DownloadCsvButton({ reportType, params, disabled }: DownloadCsvButtonProps) {
  const [downloading, setDownloading] = useState(false)

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

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