"use client"

import { useState } from "react"
import Link from "next/link"
import { ChevronDown, ChevronRight, Users } from "lucide-react"
import { useTranslations } from "next-intl"

import { Badge } from "@/shared/components/ui/badge"
import { Progress } from "@/shared/components/ui/progress"
import { cn } from "@/shared/lib/utils"

import type { StudentErrorBookSummary } from "@/modules/error-book/types"

interface GroupedStudentErrorTableProps {
  students: StudentErrorBookSummary[]
  studentNames: Map<string, string>
  basePath: string
}

interface ClassGroup {
  classId: string | null
  className: string
  students: StudentErrorBookSummary[]
  totalErrors: number
  averageMasteryRate: number
}

/**
 * 按班级分组的学生错题表格（教师视图）
 * 每个班级可展开/折叠，显示该班学生的错题详情
 */
export function GroupedStudentErrorTable({
  students,
  studentNames,
  basePath,
}: GroupedStudentErrorTableProps) {
  const t = useTranslations("errorBook")
  const [expandedClasses, setExpandedClasses] = useState<Set<string>>(new Set())

  // 按班级分组
  const groups: ClassGroup[] = []
  const groupMap = new Map<string | null, ClassGroup>()

  for (const student of students) {
    const key = student.classId
    let group = groupMap.get(key)
    if (!group) {
      group = {
        classId: key,
        className: student.className ?? t("groupedTable.unclassified"),
        students: [],
        totalErrors: 0,
        averageMasteryRate: 0,
      }
      groupMap.set(key, group)
      groups.push(group)
    }
    group.students.push(student)
    group.totalErrors += student.totalCount
  }

  // 计算每组的平均掌握率并排序
  for (const group of groups) {
    const studentsWithErrors = group.students.filter((s) => s.totalCount > 0)
    group.averageMasteryRate =
      studentsWithErrors.length > 0
        ? studentsWithErrors.reduce((sum, s) => sum + s.masteredRate, 0) / studentsWithErrors.length
        : 0
    // 按错题数降序
    group.students.sort((a, b) => b.totalCount - a.totalCount)
  }
  groups.sort((a, b) => b.totalErrors - a.totalErrors)

  const toggleClass = (classId: string | null) => {
    const key = classId ?? "unclassified"
    setExpandedClasses((prev) => {
      const next = new Set(prev)
      if (next.has(key)) {
        next.delete(key)
      } else {
        next.add(key)
      }
      return next
    })
  }

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

  return (
    <div className="space-y-3">
      {groups.map((group) => {
        const groupKey = group.classId ?? "unclassified"
        const isExpanded = expandedClasses.has(groupKey)
        const studentsWithErrors = group.students.filter((s) => s.totalCount > 0)

        return (
          <div key={groupKey} className="overflow-hidden rounded-lg border">
            {/* 班级头部（可点击展开） */}
            <button
              type="button"
              aria-expanded={isExpanded}
              onClick={() => toggleClass(group.classId)}
              className="flex w-full items-center justify-between gap-3 bg-muted/50 p-3 text-left transition-colors hover:bg-muted"
            >
              <div className="flex items-center gap-2">
                {isExpanded ? (
                  <ChevronDown className="h-4 w-4 text-muted-foreground" />
                ) : (
                  <ChevronRight className="h-4 w-4 text-muted-foreground" />
                )}
                <Users className="h-4 w-4 text-muted-foreground" />
                <span className="font-medium">{group.className}</span>
                <Badge variant="outline" className="text-xs">
                  {t("groupedTable.studentCount", { count: group.students.length })}
                </Badge>
                {studentsWithErrors.length < group.students.length ? (
                  <Badge variant="secondary" className="text-xs">
                    {t("groupedTable.studentsWithErrors", { count: studentsWithErrors.length })}
                  </Badge>
                ) : null}
              </div>
              <div className="flex items-center gap-4 text-sm">
                <div className="text-right">
                  <div className="text-xs text-muted-foreground">{t("groupedTable.totalErrors")}</div>
                  <div className="font-bold text-rose-600">{group.totalErrors}</div>
                </div>
                <div className="text-right">
                  <div className="text-xs text-muted-foreground">{t("groupedTable.avgMastery")}</div>
                  <div className="font-medium">
                    {Math.round(group.averageMasteryRate * 100)}%
                  </div>
                </div>
              </div>
            </button>

            {/* 学生表格（展开时显示） */}
            {isExpanded ? (
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead className="border-b bg-muted/30">
                    <tr className="text-left text-xs text-muted-foreground">
                      <th className="px-3 py-2 font-medium">{t("groupedTable.student")}</th>
                      <th className="px-3 py-2 text-right font-medium">{t("groupedTable.totalErrors")}</th>
                      <th className="px-3 py-2 text-right font-medium">{t("groupedTable.new")}</th>
                      <th className="px-3 py-2 text-right font-medium">{t("groupedTable.learning")}</th>
                      <th className="px-3 py-2 text-right font-medium">{t("groupedTable.mastered")}</th>
                      <th className="px-3 py-2 text-right font-medium">{t("groupedTable.dueReview")}</th>
                      <th className="px-3 py-2 font-medium">{t("groupedTable.masteryRate")}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {group.students.map((student) => {
                      const name = studentNames.get(student.studentId) ?? t("groupedTable.unknown")
                      const hasErrors = student.totalCount > 0
                      return (
                        <tr
                          key={student.studentId}
                          className={cn(
                            "border-b last:border-0 transition-colors",
                            hasErrors ? "hover:bg-muted/50" : "opacity-50"
                          )}
                        >
                          <td className="px-3 py-2">
                            {hasErrors ? (
                              <Link
                                href={`${basePath}?studentId=${student.studentId}`}
                                className="font-medium text-primary hover:underline"
                              >
                                {name}
                              </Link>
                            ) : (
                              <span className="text-muted-foreground">{name}</span>
                            )}
                          </td>
                          <td className="px-3 py-2 text-right font-medium">
                            {student.totalCount}
                          </td>
                          <td className="px-3 py-2 text-right text-blue-600 dark:text-blue-400">
                            {student.newCount}
                          </td>
                          <td className="px-3 py-2 text-right">
                            {student.learningCount}
                          </td>
                          <td className="px-3 py-2 text-right text-emerald-600 dark:text-emerald-400">
                            {student.masteredCount}
                          </td>
                          <td className="px-3 py-2 text-right text-rose-600 dark:text-rose-400">
                            {student.dueReviewCount}
                          </td>
                          <td className="px-3 py-2">
                            <div className="flex items-center gap-2">
                              <Progress
                                value={student.masteredRate * 100}
                                className="h-1.5 w-16"
                              />
                              <span className="text-xs text-muted-foreground">
                                {Math.round(student.masteredRate * 100)}%
                              </span>
                            </div>
                          </td>
                        </tr>
                      )
                    })}
                  </tbody>
                </table>
              </div>
            ) : null}
          </div>
        )
      })}
    </div>
  )
}
