import type { JSX } from "react"
import Link from "next/link"
import { useTranslations } from "next-intl"
import { CheckCircle2, XCircle, AlertCircle, Award, ArrowLeft, BookOpen } from "lucide-react"
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/shared/components/ui/card"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { Progress } from "@/shared/components/ui/progress"
import {
  formatStudentAnswer,
  getCorrectnessState,
  getQuestionText,
  getTextCorrectAnswers,
  getChoiceCorrectIds,
  getJudgmentCorrectAnswer,
} from "../lib/question-content-utils"
import type { HomeworkSubmissionDetails } from "../types"

interface HomeworkSubmissionResultProps {
  submission: HomeworkSubmissionDetails
}

/**
 * V3-9: 提交后即时反馈页
 *
 * 对标智学网/猿题库，学生提交后立即看到：
 * - 分数汇总（总分/满分、得分率）
 * - 对错分布（正确/错误/部分正确/待批改）
 * - 错题预览（题目文本、学生答案、正确答案）
 */
export function HomeworkSubmissionResult({ submission }: HomeworkSubmissionResultProps): JSX.Element {
  const t = useTranslations("examHomework")

  const maxScore = submission.answers.reduce((sum, a) => sum + a.maxScore, 0)
  const totalScore = submission.totalScore ?? 0
  const scorePercentage = maxScore > 0 ? (totalScore / maxScore) * 100 : 0

  const stats = submission.answers.reduce(
    (acc, a) => {
      const state = getCorrectnessState({ score: a.score, maxScore: a.maxScore })
      if (state === "correct") acc.correct += 1
      else if (state === "incorrect") acc.incorrect += 1
      else if (state === "partial") acc.partial += 1
      else acc.ungraded += 1
      return acc
    },
    { correct: 0, incorrect: 0, partial: 0, ungraded: 0 }
  )

  const wrongAnswers = submission.answers.filter((a) => {
    const state = getCorrectnessState({ score: a.score, maxScore: a.maxScore })
    return state === "incorrect" || state === "partial"
  })

  const formatCorrectAnswer = (questionType: string, content: unknown): string => {
    if (questionType === "single_choice" || questionType === "multiple_choice") {
      const ids = getChoiceCorrectIds(content)
      return ids.length > 0 ? ids.join(", ") : "—"
    }
    if (questionType === "judgment") {
      const ans = getJudgmentCorrectAnswer(content)
      if (ans === null) return "—"
      return ans ? t("homework.review.correctAnswerTrue") : t("homework.review.correctAnswerFalse")
    }
    if (questionType === "text") {
      const answers = getTextCorrectAnswers(content)
      return answers.length > 0 ? answers.join(" / ") : "—"
    }
    return "—"
  }

  return (
    <div className="space-y-6">
      {/* Score Summary */}
      <Card>
        <CardHeader className="text-center">
          <div className="mx-auto mb-2 flex h-16 w-16 items-center justify-center rounded-full bg-primary/10">
            <Award className="h-8 w-8 text-primary" />
          </div>
          <CardTitle className="text-3xl">
            {totalScore}
            <span className="text-lg font-normal text-muted-foreground">
              {" / "}{maxScore}
            </span>
          </CardTitle>
          <CardDescription>
            {t("homework.result.scoreRate")}: {scorePercentage.toFixed(1)}%
          </CardDescription>
        </CardHeader>
        <CardContent>
          <Progress value={scorePercentage} className="h-3" />
          {submission.status === "graded" ? (
            <p className="mt-3 text-center text-sm text-muted-foreground">
              {t("homework.result.fullyGraded")}
            </p>
          ) : (
            <p className="mt-3 text-center text-sm text-muted-foreground">
              {t("homework.result.partiallyGraded")}
            </p>
          )}
        </CardContent>
      </Card>

      {/* Stats Grid */}
      <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
        <Card>
          <CardContent className="flex items-center gap-3 pt-6">
            <CheckCircle2 className="h-8 w-8 text-green-500" />
            <div>
              <p className="text-2xl font-bold">{stats.correct}</p>
              <p className="text-xs text-muted-foreground">{t("homework.result.correctCount")}</p>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="flex items-center gap-3 pt-6">
            <XCircle className="h-8 w-8 text-red-500" />
            <div>
              <p className="text-2xl font-bold">{stats.incorrect}</p>
              <p className="text-xs text-muted-foreground">{t("homework.result.incorrectCount")}</p>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="flex items-center gap-3 pt-6">
            <AlertCircle className="h-8 w-8 text-yellow-500" />
            <div>
              <p className="text-2xl font-bold">{stats.partial}</p>
              <p className="text-xs text-muted-foreground">{t("homework.result.partialCount")}</p>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="flex items-center gap-3 pt-6">
            <BookOpen className="h-8 w-8 text-muted-foreground" />
            <div>
              <p className="text-2xl font-bold">{stats.ungraded}</p>
              <p className="text-xs text-muted-foreground">{t("homework.result.pendingCount")}</p>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Wrong Answers Preview */}
      {wrongAnswers.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>{t("homework.result.wrongAnswersTitle")}</CardTitle>
            <CardDescription>{t("homework.result.wrongAnswersDesc")}</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {wrongAnswers.map((a, index) => {
                const state = getCorrectnessState({ score: a.score, maxScore: a.maxScore })
                return (
                  <div key={a.id} className="rounded-lg border p-4">
                    <div className="mb-2 flex items-start gap-2">
                      <span className="font-medium tabular-nums">#{index + 1}</span>
                      <Badge
                        variant={state === "incorrect" ? "destructive" : "secondary"}
                        className="text-xs"
                      >
                        {state === "incorrect"
                          ? t("homework.grade.incorrect")
                          : t("homework.grade.partial")}
                      </Badge>
                      <Badge variant="outline" className="text-xs">
                        {a.questionType}
                      </Badge>
                      <span className="ml-auto text-sm tabular-nums text-muted-foreground">
                        {a.score ?? 0} / {a.maxScore}
                      </span>
                    </div>
                    <p className="mb-3 text-sm">
                      {getQuestionText(a.questionContent) || t("homework.grade.noQuestionText")}
                    </p>
                    <div className="grid gap-2 sm:grid-cols-2">
                      <div className="rounded bg-red-50 dark:bg-red-950/20 p-2">
                        <p className="mb-1 text-xs font-medium text-red-600 dark:text-red-400">
                          {t("homework.review.yourAnswer")}
                        </p>
                        <p className="text-sm">
                          {formatStudentAnswer(a.studentAnswer) || "—"}
                        </p>
                      </div>
                      <div className="rounded bg-green-50 dark:bg-green-950/20 p-2">
                        <p className="mb-1 text-xs font-medium text-green-600 dark:text-green-400">
                          {t("homework.review.correctAnswer")}
                        </p>
                        <p className="text-sm">
                          {formatCorrectAnswer(a.questionType, a.questionContent)}
                        </p>
                      </div>
                    </div>
                    {a.feedback && (
                      <div className="mt-2 rounded bg-blue-50 dark:bg-blue-950/20 p-2">
                        <p className="mb-1 text-xs font-medium text-blue-600 dark:text-blue-400">
                          {t("homework.review.teacherFeedback")}
                        </p>
                        <p className="text-sm">{a.feedback}</p>
                      </div>
                    )}
                  </div>
                )
              })}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Actions */}
      <div className="flex justify-center gap-3">
        <Button asChild variant="outline">
          <Link href="/student/learning/assignments">
            <ArrowLeft className="mr-2 h-4 w-4" />
            {t("homework.result.backToList")}
          </Link>
        </Button>
        <Button asChild>
          <Link href="/student/error-book">
            <BookOpen className="mr-2 h-4 w-4" />
            {t("homework.result.viewErrorBook")}
          </Link>
        </Button>
      </div>
    </div>
  )
}
