import { useTranslations } from "next-intl"

import { Badge } from "@/shared/components/ui/badge"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Progress } from "@/shared/components/ui/progress"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/shared/components/ui/table"
import { cn, formatDate } from "@/shared/lib/utils"

import type { StudentPracticeSummary } from "@/modules/adaptive-practice/data-access-analytics"

interface StudentPracticeRankingTableProps {
  data: StudentPracticeSummary[]
  studentNames: Map<string, string>
  className?: string
}

/**
 * 学生练习排名表格（教师视图）
 *
 * 按练习数降序排列，显示每个学生的练习数、完成数、答题数、正确率、最近练习时间。
 * 用于识别活跃学生与待引导学生。
 */
export function StudentPracticeRankingTable({
  data,
  studentNames,
  className,
}: StudentPracticeRankingTableProps) {
  const t = useTranslations("practice")

  if (data.length === 0) return null

  // 按练习数降序排列
  const sorted = [...data].sort((a, b) => b.totalSessions - a.totalSessions)

  return (
    <Card className={cn("shadow-none", className)}>
      <CardHeader>
        <CardTitle className="text-base">{t("teacher.studentRanking.title")}</CardTitle>
        <CardDescription>{t("teacher.studentRanking.description")}</CardDescription>
      </CardHeader>
      <CardContent>
        <div className="rounded-md border">
          {/* 移动端表格水平滚动 */}
          <div className="overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow className="bg-muted/50">
                  <TableHead className="w-12">{t("teacher.studentRanking.rank")}</TableHead>
                  <TableHead>{t("teacher.studentRanking.student")}</TableHead>
                  <TableHead className="text-right">{t("teacher.studentRanking.totalSessions")}</TableHead>
                  <TableHead className="text-right">{t("teacher.studentRanking.completedSessions")}</TableHead>
                  <TableHead className="text-right">{t("teacher.studentRanking.totalAnswered")}</TableHead>
                  <TableHead>{t("teacher.studentRanking.accuracy")}</TableHead>
                  <TableHead className="text-right">{t("teacher.studentRanking.lastPractice")}</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {sorted.map((student, idx) => {
                  const name = studentNames.get(student.studentId) ?? "Unknown"
                  const accuracyPct = Math.round(student.accuracy * 100)
                  const hasPractice = student.totalSessions > 0
                  return (
                    <TableRow
                      key={student.studentId}
                      className={cn(!hasPractice && "opacity-50")}
                    >
                      <TableCell className="text-muted-foreground tabular-nums">{idx + 1}</TableCell>
                      <TableCell className="font-medium">{name}</TableCell>
                      <TableCell className="text-right tabular-nums">
                        {student.totalSessions > 0 ? (
                          <Badge variant="secondary" className="tabular-nums">
                            {student.totalSessions}
                          </Badge>
                        ) : (
                          <span className="text-muted-foreground">-</span>
                        )}
                      </TableCell>
                      <TableCell className="text-right tabular-nums">{student.completedSessions}</TableCell>
                      <TableCell className="text-right tabular-nums">{student.totalQuestionsAnswered}</TableCell>
                      <TableCell>
                        {hasPractice ? (
                          <div className="flex items-center gap-2">
                            <Progress value={accuracyPct} className="h-1.5 w-16" />
                            <span
                              className={cn(
                                "text-xs tabular-nums",
                                accuracyPct >= 60
                                  ? "text-emerald-600 dark:text-emerald-400"
                                  : "text-rose-600 dark:text-rose-400",
                              )}
                            >
                              {accuracyPct}%
                            </span>
                          </div>
                        ) : (
                          <span className="text-muted-foreground">-</span>
                        )}
                      </TableCell>
                      <TableCell className="text-right text-muted-foreground">
                        {student.lastPracticeAt ? formatDate(student.lastPracticeAt) : "-"}
                      </TableCell>
                    </TableRow>
                  )
                })}
              </TableBody>
            </Table>
          </div>
        </div>
      </CardContent>
    </Card>
  )
}
