"use client"

import { useState } from "react"
import { Download, Loader2 } from "lucide-react"
import { useTranslations } from "next-intl"
import { toast } from "sonner"

import { Button } from "@/shared/components/ui/button"
import { downloadBlob } from "@/shared/lib/download"
import { useAuditAnalytics } from "@/modules/audit/services/audit-service"

interface AuditLogExportButtonProps {
  exportType: "audit" | "login" | "dataChange"
  params?: Record<string, unknown>
  variant?: "default" | "outline" | "secondary" | "ghost" | "destructive"
  size?: "default" | "sm" | "lg" | "icon"
  className?: string
}

const ACTION_MAP = {
  audit: "exportAuditLogsAction",
  login: "exportLoginLogsAction",
  dataChange: "exportDataChangeLogsAction",
} as const

export function AuditLogExportButton({
  exportType,
  params,
  variant = "outline",
  size = "sm",
  className,
}: AuditLogExportButtonProps) {
  const t = useTranslations("audit")
  const analytics = useAuditAnalytics()
  const [isPending, setIsPending] = useState(false)

  const handleExport = async (): Promise<void> => {
    setIsPending(true)
    try {
      const res = await fetch("/api/export", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ type: exportType, params: params ?? {} }),
      })

      if (!res.ok) {
        const body = await res.json().catch(() => null)
        toast.error(body?.message || t("export.failed"))
        return
      }

      const disposition = res.headers.get("Content-Disposition") || ""
      const filenameMatch = disposition.match(/filename="?([^";]+)"?/i)
      const filename = filenameMatch?.[1] ?? `export_${Date.now()}.xlsx`

      const blob = await res.blob()
      downloadBlob(blob, filename)
      analytics.trackExport(exportType, 0)
      toast.success(t("export.success"))
    } catch {
      toast.error(t("export.failed"))
    } finally {
      setIsPending(false)
    }
  }

  return (
    <Button
      type="button"
      variant={variant}
      size={size}
      className={className}
      disabled={isPending}
      onClick={() => void handleExport()}
      aria-label={t("export.button")}
      data-action-name={ACTION_MAP[exportType]}
    >
      {isPending ? (
        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
      ) : (
        <Download className="mr-2 h-4 w-4" />
      )}
      {t("export.button")}
    </Button>
  )
}
