import type { JSX } from "react"
import { GraduationCap } from "lucide-react"
import { getTranslations } from "next-intl/server"

import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/components/ui/table"
import { Separator } from "@/shared/components/ui/separator"

import type { ReportCardData, ReportCardSubjectItem } from "../lib/report-card"
import type { GradeRecordType } from "../types"

interface ReportCardViewProps {
  data: ReportCardData
}

function formatScore(score: number): string {
  return Number.isFinite(score) ? score.toFixed(1) : "—"
}

function formatRank(rank: number, total: number): string {
  if (rank <= 0 || total <= 0) return "—"
  return `${rank} / ${total}`
}

function formatDate(iso: string): string {
  try {
    const d = new Date(iso)
    if (Number.isNaN(d.getTime())) return iso
    const yyyy = d.getFullYear()
    const mm = String(d.getMonth() + 1).padStart(2, "0")
    const dd = String(d.getDate()).padStart(2, "0")
    return `${yyyy}-${mm}-${dd}`
  } catch {
    return iso
  }
}

function typeLabel(
  type: GradeRecordType,
  t: Awaited<ReturnType<typeof getTranslations<"grades">>>
): string {
  const key = `type.${type}` as const
  return t(key)
}

/**
 * P3-1: 成绩报告卡视图组件。
 *
 * 该组件渲染为纯服务器组件，输出符合 A4 打印规范的 HTML。
 * 打印样式通过 report-card-print.css 全局加载（@media print 规则）。
 *
 * 布局：
 * 1. 顶部：学校名 + "学期成绩报告卡" 标题 + 学生基本信息
 * 2. 中部：各科目成绩明细表格（科目 | 评估 | 类型 | 得分 | 排名 | 备注）
 * 3. 底部：综合统计 + 教师评语区 + 签名区 + 生成时间
 */
export async function ReportCardView({
  data,
}: ReportCardViewProps): Promise<JSX.Element> {
  const t = await getTranslations("grades")

  return (
    <div
      className="report-card mx-auto w-[210mm] min-h-[297mm] bg-white p-12 text-black shadow-lg"
      aria-label={t("reportCard.ariaLabel", { name: data.studentName })}
    >
      {/* 顶部：标题 + 学校信息 */}
      <header className="report-card-header flex flex-col items-center gap-3 pb-6 border-b-2 border-black">
        <div className="flex items-center gap-3">
          <GraduationCap className="h-8 w-8" aria-hidden="true" />
          <h1 className="text-2xl font-bold tracking-tight">
            {t("reportCard.schoolName")}
          </h1>
        </div>
        <h2 className="text-xl font-semibold">
          {t("reportCard.title")}
        </h2>
        <p className="text-sm text-gray-700">
          {t("reportCard.periodLabel", {
            year: data.academicYearName ?? "—",
            semester:
              data.semester === "1"
                ? t("semester.s1")
                : data.semester === "2"
                  ? t("semester.s2")
                  : t("reportCard.allSemesters"),
          })}
        </p>
      </header>

      {/* 学生基本信息 */}
      <section className="report-card-info py-4">
        <dl className="grid grid-cols-2 gap-x-8 gap-y-2 text-sm">
          <div className="flex">
            <dt className="w-24 font-medium text-gray-700">
              {t("reportCard.studentName")}
            </dt>
            <dd className="flex-1 border-b border-dotted border-gray-400 pb-0.5">
              {data.studentName}
            </dd>
          </div>
          <div className="flex">
            <dt className="w-24 font-medium text-gray-700">
              {t("reportCard.className")}
            </dt>
            <dd className="flex-1 border-b border-dotted border-gray-400 pb-0.5">
              {data.className}
            </dd>
          </div>
          <div className="flex">
            <dt className="w-24 font-medium text-gray-700">
              {t("reportCard.classTeacher")}
            </dt>
            <dd className="flex-1 border-b border-dotted border-gray-400 pb-0.5">
              {data.classTeacherName}
            </dd>
          </div>
          <div className="flex">
            <dt className="w-24 font-medium text-gray-700">
              {t("reportCard.generatedAt")}
            </dt>
            <dd className="flex-1 border-b border-dotted border-gray-400 pb-0.5">
              {formatDate(data.generatedAt)}
            </dd>
          </div>
        </dl>
      </section>

      <Separator className="my-4 bg-gray-300" />

      {/* 成绩明细表格 */}
      <section className="report-card-grades py-2">
        <h3 className="mb-3 text-base font-semibold">
          {t("reportCard.gradesSectionTitle")}
        </h3>
        {data.subjects.length === 0 ? (
          <p className="text-sm text-gray-600 italic">
            {t("reportCard.emptyGrades")}
          </p>
        ) : (
          <Table className="report-card-table border border-gray-400">
            <TableHeader>
              <TableRow className="border-b border-gray-400 bg-gray-100">
                <TableHead className="w-32 border-r border-gray-300 text-black">
                  {t("reportCard.columnSubject")}
                </TableHead>
                <TableHead className="border-r border-gray-300 text-black">
                  {t("reportCard.columnAssessment")}
                </TableHead>
                <TableHead className="w-20 border-r border-gray-300 text-black">
                  {t("reportCard.columnType")}
                </TableHead>
                <TableHead className="w-20 border-r border-gray-300 text-right text-black">
                  {t("reportCard.columnScore")}
                </TableHead>
                <TableHead className="w-24 border-r border-gray-300 text-right text-black">
                  {t("reportCard.columnRank")}
                </TableHead>
                <TableHead className="w-32 text-black">
                  {t("reportCard.columnRemark")}
                </TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {data.subjects.flatMap((subject, idx) =>
                renderSubjectRows(subject, idx, t)
              )}
            </TableBody>
          </Table>
        )}
      </section>

      {/* 综合统计 */}
      <section className="report-card-summary py-4">
        <h3 className="mb-3 text-base font-semibold">
          {t("reportCard.summarySectionTitle")}
        </h3>
        <div className="grid grid-cols-4 gap-3">
          <SummaryCell
            label={t("reportCard.overallAverage")}
            value={`${formatScore(data.overallAverage)}`}
          />
          <SummaryCell
            label={t("reportCard.overallRank")}
            value={formatRank(data.overallRank, data.classTotalStudents)}
          />
          <SummaryCell
            label={t("reportCard.passRate")}
            value={`${data.overallPassRate.toFixed(1)}%`}
          />
          <SummaryCell
            label={t("reportCard.excellentRate")}
            value={`${data.overallExcellentRate.toFixed(1)}%`}
          />
        </div>
      </section>

      {/* 教师评语 */}
      <section className="report-card-comments py-4">
        <h3 className="mb-2 text-base font-semibold">
          {t("reportCard.commentsTitle")}
        </h3>
        <div
          className="h-24 border border-gray-300 p-2 text-sm text-gray-500 italic"
          role="textbox"
          aria-label={t("reportCard.commentsAriaLabel")}
        >
          {t("reportCard.commentsPlaceholder")}
        </div>
      </section>

      {/* 签名区 */}
      <section className="report-card-signatures grid grid-cols-3 gap-6 pt-8">
        <SignatureArea label={t("reportCard.signatureClassTeacher")} />
        <SignatureArea label={t("reportCard.signatureParent")} />
        <SignatureArea label={t("reportCard.signaturePrincipal")} />
      </section>

      {/* 页脚 */}
      <footer className="report-card-footer pt-6 text-center text-xs text-gray-500">
        <p>
          {t("reportCard.footerNote", { date: formatDate(data.generatedAt) })}
        </p>
      </footer>
    </div>
  )
}

function SummaryCell({
  label,
  value,
}: {
  label: string
  value: string
}): JSX.Element {
  return (
    <div className="flex flex-col gap-1 border border-gray-300 bg-gray-50 p-2 text-center">
      <span className="text-xs text-gray-600">{label}</span>
      <span className="text-lg font-semibold text-black">{value}</span>
    </div>
  )
}

function SignatureArea({ label }: { label: string }): JSX.Element {
  return (
    <div className="flex flex-col items-center gap-2">
      <div className="h-12 w-32 border-b border-dotted border-gray-500" />
      <span className="text-xs text-gray-700">{label}</span>
    </div>
  )
}

function renderSubjectRows(
  subject: ReportCardSubjectItem,
  index: number,
  t: Awaited<ReturnType<typeof getTranslations<"grades">>>
): JSX.Element[] {
  if (subject.records.length === 0) {
    return [
      <TableRow key={`${subject.subjectId}-${index}`} className="border-b border-gray-300">
        <TableCell className="border-r border-gray-200 font-medium">
          {subject.subjectName}
        </TableCell>
        <TableCell className="border-r border-gray-200 text-gray-500 italic">
          {t("reportCard.noRecords")}
        </TableCell>
        <TableCell className="border-r border-gray-200">—</TableCell>
        <TableCell className="border-r border-gray-200 text-right">—</TableCell>
        <TableCell className="border-r border-gray-200 text-right">
          {formatRank(subject.rankInSubject, subject.totalStudentsInSubject)}
        </TableCell>
        <TableCell>—</TableCell>
      </TableRow>,
    ]
  }

  return subject.records.map((record, rIdx) => (
    <TableRow
      key={`${subject.subjectId}-${rIdx}`}
      className="border-b border-gray-200"
    >
      {rIdx === 0 ? (
        <TableCell
          className="border-r border-gray-200 font-medium align-top"
          rowSpan={subject.records.length}
        >
          {subject.subjectName}
          <span className="block text-xs text-gray-500 mt-1">
            {t("reportCard.subjectAvg", { score: formatScore(subject.averageScore) })}
          </span>
        </TableCell>
      ) : null}
      <TableCell className="border-r border-gray-200">{record.title}</TableCell>
      <TableCell className="border-r border-gray-200 text-xs">
        {typeLabel(record.type, t)}
      </TableCell>
      <TableCell className="border-r border-gray-200 text-right font-mono">
        {formatScore(record.score)}
        <span className="text-xs text-gray-500">
          {" / "}
          {formatScore(record.fullScore)}
        </span>
      </TableCell>
      {rIdx === 0 ? (
        <TableCell
          className="border-r border-gray-200 text-right align-top"
          rowSpan={subject.records.length}
        >
          {formatRank(subject.rankInSubject, subject.totalStudentsInSubject)}
        </TableCell>
      ) : null}
      <TableCell className="text-xs text-gray-600">
        {record.remark ?? ""}
      </TableCell>
    </TableRow>
  ))
}
