import type { JSX } from "react"
import { useTranslations } from "next-intl"
import { Users, CheckCircle2, TrendingUp, Award, AlertTriangle } from "lucide-react"
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/shared/components/ui/card"
import { Badge } from "@/shared/components/ui/badge"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/components/ui/table"
import { Progress } from "@/shared/components/ui/progress"
import type { ExamAnalyticsSummary } from "../stats-service"

interface ExamAnalyticsDashboardProps {
  analytics: ExamAnalyticsSummary
}

/**
 * V3-8: 考试分析仪表盘
 *
 * 对标智学网考试分析功能，展示：
 * - 汇总卡片（应考人数、已批改份数、平均分、及格率）
 * - 分数段分布
 * - 逐题分析（错误率、难度等级）
 */
export function ExamAnalyticsDashboard({ analytics }: ExamAnalyticsDashboardProps): JSX.Element {
  const t = useTranslations("examHomework")

  const difficultyVariant = (difficulty: "easy" | "medium" | "hard") => {
    if (difficulty === "easy") return "default" as const
    if (difficulty === "medium") return "secondary" as const
    return "destructive" as const
  }

  const difficultyLabel = (difficulty: "easy" | "medium" | "hard") => {
    if (difficulty === "easy") return t("exam.analytics.difficultyEasy")
    if (difficulty === "medium") return t("exam.analytics.difficultyMedium")
    return t("exam.analytics.difficultyHard")
  }

  return (
    <div className="space-y-6">
      {/* Summary Cards */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">
              {t("exam.analytics.totalStudents")}
            </CardTitle>
            <Users className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{analytics.totalStudents}</div>
            <p className="text-xs text-muted-foreground">
              {t("exam.analytics.submitted")}: {analytics.submittedCount} / {analytics.totalStudents}
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">
              {t("exam.analytics.gradedCount")}
            </CardTitle>
            <CheckCircle2 className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{analytics.gradedCount}</div>
            <p className="text-xs text-muted-foreground">
              {t("exam.analytics.assignmentCount")}: {analytics.assignmentCount}
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">
              {t("exam.analytics.averageScore")}
            </CardTitle>
            <TrendingUp className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {analytics.averageScore}
              <span className="text-sm font-normal text-muted-foreground">
                {" / "}{analytics.maxScore}
              </span>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">
              {t("exam.analytics.passRate")}
            </CardTitle>
            <Award className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {(analytics.passRate * 100).toFixed(1)}%
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Score Distribution */}
      <Card>
        <CardHeader>
          <CardTitle>{t("exam.analytics.scoreDistribution")}</CardTitle>
          <CardDescription>{t("exam.analytics.scoreDistributionDesc")}</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-3">
            {analytics.scoreDistribution.map((item) => {
              const maxCount = Math.max(...analytics.scoreDistribution.map((d) => d.count), 1)
              const percentage = (item.count / maxCount) * 100
              return (
                <div key={item.range} className="flex items-center gap-3">
                  <span className="w-20 text-sm text-muted-foreground tabular-nums">{item.range}</span>
                  <Progress value={percentage} className="h-3 flex-1" />
                  <span className="w-10 text-sm font-medium tabular-nums text-right">{item.count}</span>
                </div>
              )
            })}
          </div>
        </CardContent>
      </Card>

      {/* Per-Question Analysis */}
      <Card>
        <CardHeader>
          <CardTitle>{t("exam.analytics.questionAnalysis")}</CardTitle>
          <CardDescription>{t("exam.analytics.questionAnalysisDesc")}</CardDescription>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-[40px]">#</TableHead>
                <TableHead>{t("exam.analytics.questionType")}</TableHead>
                <TableHead className="min-w-[200px]">{t("exam.analytics.questionText")}</TableHead>
                <TableHead className="text-right">{t("exam.analytics.maxScore")}</TableHead>
                <TableHead className="text-right">{t("exam.analytics.errorCount")}</TableHead>
                <TableHead className="w-[120px]">{t("exam.analytics.errorRate")}</TableHead>
                <TableHead>{t("exam.analytics.difficulty")}</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {analytics.questions.map((q, index) => (
                <TableRow key={q.questionId}>
                  <TableCell className="font-medium tabular-nums">{index + 1}</TableCell>
                  <TableCell>
                    <Badge variant="outline" className="text-xs">
                      {q.questionType}
                    </Badge>
                  </TableCell>
                  <TableCell className="max-w-[300px] truncate text-sm text-muted-foreground">
                    {q.questionText}
                  </TableCell>
                  <TableCell className="text-right tabular-nums">{q.maxScore}</TableCell>
                  <TableCell className="text-right tabular-nums">{q.errorCount}</TableCell>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      <Progress
                        value={q.errorRate * 100}
                        className="h-2"
                      />
                      <span className="w-10 text-xs tabular-nums text-right">
                        {(q.errorRate * 100).toFixed(0)}%
                      </span>
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge variant={difficultyVariant(q.difficulty)}>
                      {difficultyLabel(q.difficulty)}
                    </Badge>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* High Error Rate Warning */}
      {analytics.questions.filter((q) => q.errorRate >= 0.7).length > 0 && (
        <Card className="border-destructive/50">
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-destructive">
              <AlertTriangle className="h-5 w-5" />
              {t("exam.analytics.highErrorWarning")}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-sm text-muted-foreground mb-3">
              {t("exam.analytics.highErrorWarningDesc")}
            </p>
            <div className="space-y-2">
              {analytics.questions
                .filter((q) => q.errorRate >= 0.7)
                .map((q, index) => (
                  <div key={q.questionId} className="flex items-center gap-2 text-sm">
                    <span className="font-medium tabular-nums">#{index + 1}</span>
                    <span className="truncate text-muted-foreground">{q.questionText}</span>
                    <Badge variant="destructive" className="ml-auto">
                      {(q.errorRate * 100).toFixed(0)}%
                    </Badge>
                  </div>
                ))}
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  )
}
