"use client"

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

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 { 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) {
  const [isExporting, setIsExporting] = useState(false)

  const handleExport = async (reportType: "detail" | "class") => {
    if (!classId) {
      toast.error("请先选择班级")
      return
    }
    setIsExporting(true)
    const result = await exportGradesAction({
      classId,
      subjectId,
      examId,
      reportType,
    })
    setIsExporting(false)

    if (result.success && result.data) {
      downloadBase64File(result.data.buffer, result.data.filename)
      toast.success("导出成功")
    } else {
      toast.error(result.message ?? "导出失败")
    }
  }

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

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button variant={variant} size={size}>
          <Download className="mr-2 h-4 w-4" />
          {label}
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end">
        <DropdownMenuItem onClick={() => handleExport("detail")}>
          成绩明细
        </DropdownMenuItem>
        <DropdownMenuItem onClick={() => handleExport("class")}>
          班级成绩总表
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  )
}
