import Link from "next/link"
import { Users, AlertTriangle, TrendingUp, Target } from "lucide-react"

import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { StatCard } from "@/shared/components/ui/stat-card"
import { Badge } from "@/shared/components/ui/badge"
import { Progress } from "@/shared/components/ui/progress"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { formatDate, formatNumber } from "@/shared/lib/utils"
import type {
  StudentErrorBookSummary,
  KnowledgePointWeakness,
  SubjectErrorDistribution,
} from "../types"

interface ClassErrorBookOverviewProps {
  totalStudents: number
  studentsWithErrorBook: number
  totalErrorItems: number
  averageMasteryRate: number
  topWeakKnowledgePoints: KnowledgePointWeakness[]
  subjectDistribution: SubjectErrorDistribution[]
}

export function ClassErrorBookOverview({
  totalStudents,
  studentsWithErrorBook,
  totalErrorItems,
  averageMasteryRate,
  topWeakKnowledgePoints,
  subjectDistribution,
}: ClassErrorBookOverviewProps) {
  return (
    <div className="space-y-6">
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <StatCard
          title="覆盖学生"
          value={`${studentsWithErrorBook}/${totalStudents}`}
          icon={Users}
          description="有错题记录的学生数"
        />
        <StatCard
          title="错题总数"
          value={totalErrorItems}
          icon={AlertTriangle}
          color="text-rose-500"
          description="班级累计错题"
        />
        <StatCard
          title="平均掌握率"
          value={`${formatNumber(averageMasteryRate * 100, 0)}%`}
          icon={TrendingUp}
          color="text-emerald-500"
          description="已掌握错题占比"
        />
        <StatCard
          title="薄弱知识点"
          value={topWeakKnowledgePoints.length}
          icon={Target}
          color="text-amber-500"
          description="需重点讲解"
        />
      </div>

      <div className="grid gap-4 md:grid-cols-2">
        {/* 薄弱知识点 */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-base">
              <Target className="h-4 w-4" />
              薄弱知识点 Top 10
            </CardTitle>
          </CardHeader>
          <CardContent>
            {topWeakKnowledgePoints.length === 0 ? (
              <p className="text-sm text-muted-foreground py-6 text-center">
                暂无数据
              </p>
            ) : (
              <div className="space-y-3">
                {topWeakKnowledgePoints.map((kp, idx) => (
                  <div key={kp.knowledgePointId} className="space-y-1">
                    <div className="flex items-center justify-between text-sm">
                      <span className="flex items-center gap-2">
                        <Badge variant="outline" className="w-6 justify-center">
                          {idx + 1}
                        </Badge>
                        <span className="line-clamp-1">{kp.knowledgePointName}</span>
                      </span>
                      <span className="text-muted-foreground">
                        {kp.errorCount} 错 · {formatNumber(kp.masteryRate * 100, 0)}% 掌握
                      </span>
                    </div>
                    <Progress value={kp.masteryRate * 100} className="h-1.5" />
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>

        {/* 学科分布 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">学科错题分布</CardTitle>
          </CardHeader>
          <CardContent>
            {subjectDistribution.length === 0 ? (
              <p className="text-sm text-muted-foreground py-6 text-center">
                暂无数据
              </p>
            ) : (
              <div className="space-y-3">
                {subjectDistribution.map((s) => (
                  <div key={s.subjectId ?? "none"} className="space-y-1">
                    <div className="flex items-center justify-between text-sm">
                      <span>{s.subjectName}</span>
                      <span className="text-muted-foreground">
                        {s.errorCount} 错 · {formatNumber(s.masteryRate * 100, 0)}% 掌握
                      </span>
                    </div>
                    <Progress value={s.masteryRate * 100} className="h-1.5" />
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  )
}

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

export function StudentErrorTable({ students, studentNames, basePath }: StudentErrorTableProps) {
  if (students.length === 0) {
    return (
      <EmptyState
        icon={Users}
        title="暂无学生错题数据"
        description="学生完成作业或考试后，错题数据会自动汇总到这里。"
        className="h-[300px] bg-card"
      />
    )
  }

  return (
    <div className="rounded-md border bg-card">
      <table className="w-full text-sm">
        <thead>
          <tr className="border-b bg-muted/50">
            <th className="px-4 py-3 text-left font-medium">学生</th>
            <th className="px-4 py-3 text-right font-medium">错题总数</th>
            <th className="px-4 py-3 text-right font-medium">待学习</th>
            <th className="px-4 py-3 text-right font-medium">学习中</th>
            <th className="px-4 py-3 text-right font-medium">已掌握</th>
            <th className="px-4 py-3 text-right font-medium">待复习</th>
            <th className="px-4 py-3 text-right font-medium">掌握率</th>
            <th className="px-4 py-3 text-right font-medium">最近活动</th>
          </tr>
        </thead>
        <tbody>
          {students.map((s) => {
            const name = studentNames.get(s.studentId) ?? "未知"
            return (
              <tr key={s.studentId} className="border-b last:border-0 hover:bg-muted/30">
                <td className="px-4 py-3">
                  <Link
                    href={`${basePath}?studentId=${s.studentId}`}
                    className="font-medium hover:underline"
                  >
                    {name}
                  </Link>
                </td>
                <td className="px-4 py-3 text-right">{s.totalCount}</td>
                <td className="px-4 py-3 text-right text-blue-600 dark:text-blue-400">{s.newCount}</td>
                <td className="px-4 py-3 text-right text-amber-600 dark:text-amber-400">{s.learningCount}</td>
                <td className="px-4 py-3 text-right text-emerald-600 dark:text-emerald-400">{s.masteredCount}</td>
                <td className="px-4 py-3 text-right text-rose-600 dark:text-rose-400">{s.dueReviewCount}</td>
                <td className="px-4 py-3 text-right">
                  {formatNumber(s.masteredRate * 100, 0)}%
                </td>
                <td className="px-4 py-3 text-right text-muted-foreground text-xs">
                  {s.lastActivityAt ? formatDate(s.lastActivityAt) : "-"}
                </td>
              </tr>
            )
          })}
        </tbody>
      </table>
    </div>
  )
}
