"use client"

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

import { Button } from "@/shared/components/ui/button"
import { safeActionCall } from "@/shared/lib/action-utils"
import { exportGradesAction } from "@/modules/grades/actions"

/**
 * 家长视角的成绩导出按钮。
 * v4-P1-12: 接入 exportGradesAction，支持按 studentId 导出子女成绩。
 */
export function ParentExportButton({
  studentId,
  studentName,
  variant = "outline",
  size = "sm",
}: {
  studentId: string
  studentName: string
  variant?: "default" | "outline" | "secondary" | "ghost"
  size?: "default" | "sm" | "lg" | "icon"
}) {
  const [isExporting, setIsExporting] = useState(false)

  const handleExport = async () => {
    setIsExporting(true)
    const result = await safeActionCall(
      () => exportGradesAction({ studentId }),
      {
        onError: () => toast.error(`Failed to export grades for ${studentName}.`),
        onFinally: () => setIsExporting(false),
      }
    )
    if (result?.success && result.data) {
      try {
        // 将 base64 buffer 转换为 Blob 并触发下载
        const binaryString = atob(result.data.buffer)
        const bytes = new Uint8Array(binaryString.length)
        for (let i = 0; i < binaryString.length; i += 1) {
          bytes[i] = binaryString.charCodeAt(i)
        }
        const blob = new Blob([bytes], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        })
        const url = URL.createObjectURL(blob)
        const link = document.createElement("a")
        link.href = url
        link.download = result.data.filename
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        URL.revokeObjectURL(url)
        toast.success(`Grades exported for ${studentName}.`)
      } catch {
        toast.error("Failed to download the export file.")
      }
    } else if (result) {
      toast.error(result.message || `Failed to export grades for ${studentName}.`)
    }
  }

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

  return (
    <Button
      variant={variant}
      size={size}
      onClick={handleExport}
      aria-label={`Export ${studentName}'s grades`}
    >
      <Download className="mr-2 h-4 w-4" />
      Export
    </Button>
  )
}
