"use client"

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

import { Button } from "@/shared/components/ui/button"

/**
 * P3-1: 报告卡打印按钮（客户端组件）。
 *
 * 渲染在报告卡页面顶部，点击后调用浏览器原生 window.print()。
 * 通过 globals.css 中的 @media print 规则实现 A4 打印布局。
 */
export function ReportCardPrintAction(): JSX.Element {
  const t = useTranslations("grades")
  const [isPreparing, setIsPreparing] = useState(false)

  const handlePrint = () => {
    if (typeof window === "undefined") return
    setIsPreparing(true)
    try {
      window.print()
    } catch {
      toast.error(t("reportCard.errorPrint"))
    } finally {
      // 等待一帧后重置状态，确保用户感知到"准备中"反馈
      window.requestAnimationFrame(() => {
        setIsPreparing(false)
      })
    }
  }

  return (
    <Button onClick={handlePrint} disabled={isPreparing} className="gap-2">
      {isPreparing ? (
        <Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />
      ) : (
        <Printer className="h-4 w-4" aria-hidden="true" />
      )}
      {isPreparing
        ? t("reportCard.preparing")
        : t("reportCard.print")}
    </Button>
  )
}
