"use client"

import type { JSX, RefObject, KeyboardEvent, ClipboardEvent } from "react"
import { useTranslations } from "next-intl"

import { Card, CardContent } from "@/shared/components/ui/card"
import { Input } from "@/shared/components/ui/input"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/components/ui/table"
import { cn } from "@/shared/lib/utils"

import type { ExamForGradeEntry } from "@/modules/exams/types"

type Student = { id: string; name: string; email: string }

interface Props {
  exam: ExamForGradeEntry
  students: Student[]
  scores: Record<string, Record<string, string>>
  inputRefs: RefObject<Record<string, HTMLInputElement | null>>
  onScoreChange: (studentId: string, questionId: string, value: string) => void
  onKeyDown: (e: KeyboardEvent, studentId: string, questionId: string) => void
  onPaste: (e: ClipboardEvent, studentId: string, questionId: string) => void
  computeTotal: (studentId: string) => number
  isScoreInvalid: (studentId: string, questionId: string) => boolean
}

/**
 * 按试卷录入的成绩表格。
 *
 * P1-6 重构：从 batch-grade-entry.tsx 拆分而来。
 * Excel 式表格，支持多行多列分数粘贴、Enter 跳行。
 */
export function BatchGradeEntryTable({
  exam,
  students,
  scores,
  inputRefs,
  onScoreChange,
  onKeyDown,
  onPaste,
  computeTotal,
  isScoreInvalid,
}: Props): JSX.Element {
  const t = useTranslations("grades")

  return (
    <Card className="shadow-none">
      <CardContent className="p-0">
        <div className="overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow className="bg-muted/50">
                <TableHead className="w-12 text-center">#</TableHead>
                <TableHead className="min-w-32">{t("batchByExam.studentName")}</TableHead>
                {exam.questions.map((q, idx) => (
                  <TableHead key={q.id} className="text-center min-w-20">
                    <div className="font-medium">{t("batchByExam.question", { n: idx + 1 })}</div>
                    <div className="text-xs text-muted-foreground tabular-nums">
                      ({q.score}{t("batchByExam.points")})
                    </div>
                  </TableHead>
                ))}
                <TableHead className="text-center min-w-20">{t("batchByExam.totalScore")}</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {students.map((s, sIdx) => {
                const total = computeTotal(s.id)
                return (
                  <TableRow key={s.id}>
                    <TableCell className="text-center text-muted-foreground tabular-nums">
                      {sIdx + 1}
                    </TableCell>
                    <TableCell className="font-medium">{s.name}</TableCell>
                    {exam.questions.map((q) => {
                      const invalid = isScoreInvalid(s.id, q.id)
                      const key = `${s.id}-${q.id}`
                      const questionIdx = exam.questions.findIndex((qq) => qq.id === q.id) + 1
                      return (
                        <TableCell key={q.id} className="p-1">
                          <Input
                            ref={(el) => {
                              inputRefs.current[key] = el
                            }}
                            type="number"
                            step="0.5"
                            min="0"
                            max={q.score}
                            value={scores[s.id]?.[q.id] ?? ""}
                            onChange={(e) => onScoreChange(s.id, q.id, e.target.value)}
                            onKeyDown={(e) => onKeyDown(e, s.id, q.id)}
                            onPaste={(e) => onPaste(e, s.id, q.id)}
                            onFocus={(e) => e.target.select()}
                            className={cn(
                              "h-8 text-center tabular-nums",
                              invalid && "border-destructive focus-visible:ring-destructive"
                            )}
                            aria-label={`${s.name} - ${t("batchByExam.question", { n: questionIdx })}`}
                          />
                        </TableCell>
                      )
                    })}
                    <TableCell className="text-center font-medium tabular-nums">
                      {Math.round(total * 10) / 10}
                    </TableCell>
                  </TableRow>
                )
              })}
            </TableBody>
          </Table>
        </div>
      </CardContent>
    </Card>
  )
}
