"use client"

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

import { Button } from "@/shared/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { downloadBase64File } from "@/shared/lib/download"
import { safeActionCall } from "@/shared/lib/action-utils"
import { exportGradesAction } from "../actions"

type ExportButtonProps = {
  classId: string
  subjectId?: string
  examId?: string
  variant?: "default" | "outline" | "secondary" | "ghost"
  size?: "default" | "sm" | "lg" | "icon"
  label?: string
}

export function ExportButton({
  classId,
  subjectId,
  examId,
  variant = "outline",
  size = "default",
  label,
}: ExportButtonProps): JSX.Element {
  const t = useTranslations("grades")
  const [isExporting, setIsExporting] = useState(false)

  const handleExport = async (reportType: "detail" | "class"): Promise<void> => {
    if (!classId) {
      toast.error(t("export.selectClassFirst"))
      return
    }
    setIsExporting(true)
    // P3 修复：使用 safeActionCall 包装，确保异常时也能重置 loading 状态
    const result = await safeActionCall(
      () =>
        exportGradesAction({
          classId,
          subjectId,
          examId,
          reportType,
        }),
      {
        onError: () => toast.error(t("export.failed")),
        onFinally: () => setIsExporting(false),
      }
    )

    if (result?.success && result.data) {
      downloadBase64File(result.data.buffer, result.data.filename)
      toast.success(t("export.success"))
    } else if (result) {
      toast.error(result.message ?? t("export.failed"))
    }
  }

  if (isExporting) {
    return (
      <Button variant={variant} size={size} disabled>
        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
        {t("export.exporting")}
      </Button>
    )
  }

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button variant={variant} size={size}>
          <Download className="mr-2 h-4 w-4" />
          {label ?? t("export.defaultLabel")}
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end">
        <DropdownMenuItem onClick={() => handleExport("detail")}>
          {t("export.detailItem")}
        </DropdownMenuItem>
        <DropdownMenuItem onClick={() => handleExport("class")}>
          {t("export.classReportItem")}
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  )
}
