// ExportGradesButton：导出成绩按钮
// 依据：参考项目差距补齐 - 成绩导出
// - 点击触发 EXPORT_CHILD_GRADES mutation
// - 成功后在新窗口打开下载链接
// - loading 状态禁用按钮
// - 错误态显示提示

"use client";

import { useState } from "react";
import { useExportChildGrades } from "@/hooks/useExportChildGrades";
import { cn } from "@/lib/utils";

interface ExportGradesButtonProps {
  childId: string;
  subject?: string;
  childName?: string;
}

export function ExportGradesButton({
  childId,
  subject,
  childName,
}: ExportGradesButtonProps): JSX.Element {
  const { exportGrades, loading } = useExportChildGrades();
  const [errorMsg, setErrorMsg] = useState<string | null>(null);

  const handleExport = async (): Promise<void> => {
    setErrorMsg(null);
    const result = await exportGrades({ childId, subject });
    if (result.success && result.data) {
      // 新窗口打开下载链接
      window.open(result.data.downloadUrl, "_blank", "noopener,noreferrer");
      return;
    }
    if (result.error) {
      setErrorMsg(result.error.message);
    }
  };

  return (
    <div className="flex flex-col gap-1">
      <button
        type="button"
        onClick={handleExport}
        disabled={loading || !childId}
        className={cn(
          "rounded border border-accent px-3 py-1.5 text-sm font-medium",
          "bg-accent-soft text-accent transition-colors",
          "hover:bg-accent hover:text-paper",
          "disabled:cursor-not-allowed disabled:opacity-50",
        )}
        aria-label={`导出${childName ?? ""}成绩`}
      >
        {loading ? "导出中..." : "导出成绩"}
      </button>
      {errorMsg && (
        <p role="alert" className="text-xs text-danger">
          导出失败：{errorMsg}
        </p>
      )}
    </div>
  );
}

export default ExportGradesButton;
