import Link from "next/link"
import { useTranslations } from "next-intl"
import { ArrowLeft, Pencil, Users } from "lucide-react"

import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { EmptyState } from "@/shared/components/ui/empty-state"

import {
  COURSE_SELECTION_STATUS_BADGE_VARIANTS,
  COURSE_SELECTION_STATUS_LABEL_KEYS,
  ELECTIVE_STATUS_BADGE_VARIANTS,
  ELECTIVE_STATUS_LABEL_KEYS,
  SELECTION_MODE_LABEL_KEYS,
} from "../constants"
import type {
  CourseSelectionWithDetails,
  ElectiveCourseWithDetails,
} from "../types"

/**
 * 选修课程详情视图（admin/teacher 共用）。
 *
 * 设计原则：
 * - 通过 props 注入数据，不直接调用 data-access（便于测试与复用）
 * - 组合优先：分成课程信息卡片 + 选课名单表格两个独立区块
 * - 编辑按钮通过 editHref 参数化，admin/teacher 路由各自传入
 */
export function ElectiveCourseDetail({
  course,
  selections,
  editHref,
  backHref,
  showEditButton = true,
}: {
  course: ElectiveCourseWithDetails
  selections: CourseSelectionWithDetails[]
  editHref?: string
  backHref: string
  showEditButton?: boolean
}) {
  const t = useTranslations("elective")

  const activeSelections = selections.filter((s) =>
    ["selected", "enrolled", "waitlist"].includes(s.status)
  )

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <Button asChild variant="ghost" size="sm">
          <Link href={backHref}>
            <ArrowLeft className="mr-1 h-4 w-4" />
            {t("detail.back")}
          </Link>
        </Button>
        {showEditButton && editHref ? (
          <Button asChild size="sm">
            <Link href={editHref}>
              <Pencil className="mr-1 h-4 w-4" />
              {t("detail.editCourse")}
            </Link>
          </Button>
        ) : null}
      </div>

      <Card>
        <CardHeader className="flex flex-row items-start justify-between gap-2 space-y-0">
          <div className="space-y-1">
            <CardTitle className="text-2xl">{course.name}</CardTitle>
            <p className="text-sm text-muted-foreground">
              {t("description.detail")}
            </p>
          </div>
          <Badge variant={ELECTIVE_STATUS_BADGE_VARIANTS[course.status]} className="shrink-0">
            {t(ELECTIVE_STATUS_LABEL_KEYS[course.status])}
          </Badge>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
            <DetailField label={t("fields.subject")} value={course.subjectName} />
            <DetailField label={t("fields.grade")} value={course.gradeName} />
            <DetailField label={t("fields.teacher")} value={course.teacherName} />
            <DetailField
              label={t("fields.capacity")}
              value={`${course.enrolledCount} / ${course.capacity}`}
            />
            <DetailField label={t("fields.classroom")} value={course.classroom} />
            <DetailField
              label={t("fields.selectionMode")}
              value={t(SELECTION_MODE_LABEL_KEYS[course.selectionMode])}
            />
            <DetailField label={t("fields.credit")} value={course.credit} />
            <DetailField label={t("fields.startDate")} value={course.startDate} />
            <DetailField label={t("fields.endDate")} value={course.endDate} />
            <DetailField label={t("fields.selectionStart")} value={course.selectionStartAt} />
            <DetailField label={t("fields.selectionEnd")} value={course.selectionEndAt} />
          </div>
          {course.schedule ? (
            <div className="mt-4">
              <p className="text-sm font-medium text-muted-foreground">{t("fields.schedule")}</p>
              <p className="mt-1 text-sm">{course.schedule}</p>
            </div>
          ) : null}
          {course.description ? (
            <div className="mt-4">
              <p className="text-sm font-medium text-muted-foreground">{t("fields.description")}</p>
              <p className="mt-1 text-sm">{course.description}</p>
            </div>
          ) : null}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle className="flex items-center gap-2 text-lg">
              <Users className="h-5 w-5" />
              {t("detail.studentsTitle")}
            </CardTitle>
            <span className="text-sm text-muted-foreground">
              {activeSelections.length}
            </span>
          </div>
        </CardHeader>
        <CardContent>
          {activeSelections.length === 0 ? (
            <EmptyState
              title={t("detail.noStudents")}
              description={t("detail.noStudentsDescription")}
              icon={Users}
              className="h-auto border-none shadow-none"
            />
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b text-left text-muted-foreground">
                    <th className="pb-2 pr-4 font-medium">#</th>
                    <th className="pb-2 pr-4 font-medium">{t("detail.studentName")}</th>
                    <th className="pb-2 pr-4 font-medium">{t("export.statusHeader")}</th>
                    <th className="pb-2 pr-4 font-medium">{t("detail.priority")}</th>
                    <th className="pb-2 pr-4 font-medium">{t("detail.selectedAt")}</th>
                    <th className="pb-2 pr-4 font-medium">{t("detail.enrolledAt")}</th>
                  </tr>
                </thead>
                <tbody>
                  {activeSelections.map((sel, idx) => (
                    <tr key={sel.id} className="border-b last:border-0">
                      <td className="py-2 pr-4 text-muted-foreground">{idx + 1}</td>
                      <td className="py-2 pr-4 font-medium">
                        {sel.studentName ?? "—"}
                      </td>
                      <td className="py-2 pr-4">
                        <Badge variant={COURSE_SELECTION_STATUS_BADGE_VARIANTS[sel.status]}>
                          {t(COURSE_SELECTION_STATUS_LABEL_KEYS[sel.status])}
                        </Badge>
                      </td>
                      <td className="py-2 pr-4 tabular-nums">
                        {sel.priority ?? "—"}
                      </td>
                      <td className="py-2 pr-4 text-muted-foreground">
                        {sel.selectedAt
                          ? new Date(sel.selectedAt).toLocaleDateString()
                          : "—"}
                      </td>
                      <td className="py-2 pr-4 text-muted-foreground">
                        {sel.enrolledAt
                          ? new Date(sel.enrolledAt).toLocaleDateString()
                          : "—"}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}

function DetailField({
  label,
  value,
}: {
  label: string
  value: string | null | undefined
}) {
  return (
    <div>
      <p className="text-xs font-medium text-muted-foreground">{label}</p>
      <p className="mt-1 text-sm font-medium">{value ?? "—"}</p>
    </div>
  )
}
