"use client"

import type { JSX } from "react"
import { useState, useTransition } from "react"
import { useRouter } from "next/navigation"
import { Printer } from "lucide-react"
import { toast } from "sonner"
import { useTranslations } from "next-intl"

import { Button } from "@/shared/components/ui/button"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/components/ui/select"
import { Label } from "@/shared/components/ui/label"

interface ReportCardPrintButtonProps {
  /** 学生 ID */
  studentId: string
  /** 可选的学年列表 */
  academicYears: Array<{ id: string; name: string }>
}

/**
 * P3-1: 成绩报告卡打印按钮（客户端组件）。
 *
 * 该组件不直接调用 window.print()，而是通过路由跳转到
 * /teacher/grades/report-card?studentId=xxx&academicYearId=yyy&semester=zzz
 * 由报告卡页面渲染完整 A4 视图后，用户点击页面上的"打印"按钮触发浏览器打印。
 *
 * 这种方式的好处：
 * 1. 报告卡页面是独立路由，可被书签收藏、家长直接访问
 * 2. 打印样式仅在该页面生效，避免污染其他页面
 * 3. 路由层完成权限校验，避免客户端绕过
 */
export function ReportCardPrintButton({
  studentId,
  academicYears,
}: ReportCardPrintButtonProps): JSX.Element {
  const t = useTranslations("grades")
  const router = useRouter()
  const [isPending, startTransition] = useTransition()
  const [academicYearId, setAcademicYearId] = useState<string>("all")
  const [semester, setSemester] = useState<string>("all")

  const handleNavigate = () => {
    startTransition(() => {
      const params = new URLSearchParams()
      params.set("studentId", studentId)
      if (academicYearId !== "all") params.set("academicYearId", academicYearId)
      if (semester !== "all") params.set("semester", semester)
      try {
        router.push(`/teacher/grades/report-card?${params.toString()}`)
      } catch {
        toast.error(t("reportCard.errorNavigate"))
      }
    })
  }

  return (
    <div className="flex flex-wrap items-end gap-3">
      <div className="grid gap-1.5">
        <Label htmlFor="rc-academic-year" className="text-xs">
          {t("reportCard.filterAcademicYear")}
        </Label>
        <Select value={academicYearId} onValueChange={setAcademicYearId}>
          <SelectTrigger id="rc-academic-year" className="w-[180px]">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">{t("reportCard.filterAllAcademicYears")}</SelectItem>
            {academicYears.map((y) => (
              <SelectItem key={y.id} value={y.id}>
                {y.name}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      <div className="grid gap-1.5">
        <Label htmlFor="rc-semester" className="text-xs">
          {t("reportCard.filterSemester")}
        </Label>
        <Select value={semester} onValueChange={setSemester}>
          <SelectTrigger id="rc-semester" className="w-[140px]">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">{t("reportCard.filterAllSemesters")}</SelectItem>
            <SelectItem value="1">{t("semester.s1")}</SelectItem>
            <SelectItem value="2">{t("semester.s2")}</SelectItem>
          </SelectContent>
        </Select>
      </div>

      <Button onClick={handleNavigate} disabled={isPending} className="gap-2">
        <Printer className="h-4 w-4" aria-hidden="true" />
        {t("reportCard.openReportCard")}
      </Button>
    </div>
  )
}
