"use client"

import Link from "next/link"
import { Book, Clock, GraduationCap, Trophy, HelpCircle } from "lucide-react"
import { useTranslations } from "next-intl"
import {
  Card,
  CardContent,
  CardFooter,
  CardHeader,
} from "@/shared/components/ui/card"
import { Badge, BadgeProps } from "@/shared/components/ui/badge"
import { cn, formatDate } from "@/shared/lib/utils"
import { Exam } from "../types"
import { ExamActions } from "./exam-actions"

interface ExamCardProps {
  exam: Exam
  hrefBase?: string
}

/**
 * P1-3 重构：按 subjectId 做确定性哈希选色，替代按英文名映射。
 * 确保同一科目在任意语言下颜色一致，且无需维护硬编码科目名映射表。
 */
const SUBJECT_COLOR_PALETTE: readonly string[] = [
  "from-blue-500/20 to-blue-600/20 text-blue-700 dark:text-blue-300 border-blue-200 dark:border-blue-800",
  "from-purple-500/20 to-purple-600/20 text-purple-700 dark:text-purple-300 border-purple-200 dark:border-purple-800",
  "from-teal-500/20 to-teal-600/20 text-teal-700 dark:text-teal-300 border-teal-200 dark:border-teal-800",
  "from-orange-500/20 to-orange-600/20 text-orange-700 dark:text-orange-300 border-orange-200 dark:border-orange-800",
  "from-amber-500/20 to-amber-600/20 text-amber-700 dark:text-amber-300 border-amber-200 dark:border-amber-800",
  "from-emerald-500/20 to-emerald-600/20 text-emerald-700 dark:text-emerald-300 border-emerald-200 dark:border-emerald-800",
  "from-sky-500/20 to-sky-600/20 text-sky-700 dark:text-sky-300 border-sky-200 dark:border-sky-800",
  "from-rose-500/20 to-rose-600/20 text-rose-700 dark:text-rose-300 border-rose-200 dark:border-rose-800",
]

const DEFAULT_COLOR_CLASS =
  "from-zinc-500/20 to-zinc-600/20 text-zinc-700 dark:text-zinc-300 border-zinc-200 dark:border-zinc-800"

const getSubjectColorClass = (subjectId: string | null): string => {
  if (!subjectId) return DEFAULT_COLOR_CLASS
  let hash = 0
  for (let i = 0; i < subjectId.length; i += 1) {
    hash = (hash * 31 + subjectId.charCodeAt(i)) | 0
  }
  const index = Math.abs(hash) % SUBJECT_COLOR_PALETTE.length
  return SUBJECT_COLOR_PALETTE[index]!
}

export function ExamCard({ exam, hrefBase }: ExamCardProps) {
  const t = useTranslations("examHomework")
  const base = hrefBase || "/teacher/exams"
  const colorClass = getSubjectColorClass(exam.subjectId)

  const statusVariant: BadgeProps["variant"] =
    exam.status === "published"
      ? "secondary"
      : exam.status === "archived"
      ? "destructive"
      : "outline"

  return (
    <Card className="group flex flex-col h-full overflow-hidden transition-all duration-300 hover:shadow-md hover:border-primary/50">
      <Link href={`${base}/${exam.id}/build`} className="flex-1">
        <div className={cn("relative h-32 w-full overflow-hidden bg-gradient-to-br p-6 transition-all group-hover:scale-105", colorClass)}>
          <div className="absolute inset-0 bg-grid-black/[0.05] dark:bg-grid-white/[0.05]" />
          <div className="relative z-10 flex h-full flex-col justify-between">
            <div className="flex justify-between items-start">
                <Badge variant={statusVariant} className="bg-background/50 backdrop-blur-sm shadow-none border-transparent">
                    {t(`exam.status.${exam.status}` as const)}
                </Badge>
                {exam.difficulty && (
                    <Badge variant="outline" className="bg-background/50 backdrop-blur-sm border-transparent shadow-none">
                        {t("exam.card.level", { level: exam.difficulty })}
                    </Badge>
                )}
            </div>
            <Book className="h-8 w-8 opacity-50" />
          </div>
        </div>

        <CardHeader className="p-4 pb-2">
          <div className="flex items-start justify-between gap-2">
            <h3 className="font-semibold text-lg leading-tight line-clamp-2 group-hover:text-primary transition-colors">
              {exam.title}
            </h3>
          </div>
        </CardHeader>

        <CardContent className="p-4 pt-1 pb-2">
          <div className="flex flex-wrap gap-y-2 gap-x-4 text-xs text-muted-foreground">
            <div className="flex items-center gap-1.5">
              <GraduationCap className="h-3.5 w-3.5" />
              <span>{exam.grade}</span>
            </div>
            <div className="flex items-center gap-1.5">
              <Clock className="h-3.5 w-3.5" />
              <span>{t("exam.card.minutes", { count: exam.durationMin })}</span>
            </div>
            <div className="flex items-center gap-1.5">
              <Trophy className="h-3.5 w-3.5" />
              <span>{t("exam.card.points", { count: exam.totalScore })}</span>
            </div>
          </div>
        </CardContent>
      </Link>

      <CardFooter className="p-4 pt-2 mt-auto border-t bg-muted/20 flex items-center justify-between">
        <div className="flex items-center gap-2 text-xs text-muted-foreground tabular-nums">
          <HelpCircle className="h-3.5 w-3.5" />
          <span>{t("exam.card.questions", { count: exam.questionCount || 0 })}</span>
        </div>

        <div className="flex items-center gap-1">
           <span className="text-[10px] text-muted-foreground/60 mr-2">
            {formatDate(exam.updatedAt || exam.createdAt)}
           </span>
           <ExamActions exam={exam} />
        </div>
      </CardFooter>
    </Card>
  )
}
