import type { StatusVariantMap, StatusLabelMap } from "@/shared/components/ui/status-badge"

export type HomeworkAssignmentStatus = "draft" | "published" | "archived"

export type HomeworkSubmissionStatus = "started" | "submitted" | "graded"

/** 学生作业进度状态 → Badge variant 映射（统一 not_started/in_progress/submitted/graded 颜色） */
export const STUDENT_HOMEWORK_PROGRESS_VARIANT: StatusVariantMap<StudentHomeworkProgressStatus> = {
  not_started: "outline",
  in_progress: "secondary",
  submitted: "secondary",
  graded: "default",
}

/** 学生作业进度状态 → 展示文本映射 */
export const STUDENT_HOMEWORK_PROGRESS_LABEL: StatusLabelMap<StudentHomeworkProgressStatus> = {
  not_started: "Not Started",
  in_progress: "In Progress",
  submitted: "Submitted",
  graded: "Graded",
}

export interface TeacherGradeTrendItem {
  id: string
  title: string
  averageScore: number
  maxScore: number
  submissionCount: number
  totalStudents: number
  createdAt: string
}

export interface HomeworkAssignmentListItem {
  id: string
  sourceExamId: string | null
  sourceExamTitle: string | null
  title: string
  status: HomeworkAssignmentStatus
  availableAt: string | null
  dueAt: string | null
  allowLate: boolean
  lateDueAt: string | null
  maxAttempts: number
  createdAt: string
  updatedAt: string
  /** 应提交学生数（targets 表计数） */
  targetCount: number
  /** 已提交学生数（submitted/graded 状态去重计数） */
  submittedCount: number
  /** 已批改学生数（graded 状态去重计数） */
  gradedCount: number
  /** 已批改提交的平均分（null 表示无批改数据） */
  averageScore: number | null
  /** 逾期未提交学生数（dueAt 已过且未提交） */
  overdueCount: number
}

export interface HomeworkAssignmentReviewListItem {
  id: string
  title: string
  status: HomeworkAssignmentStatus
  sourceExamTitle: string | null
  dueAt: string | null
  targetCount: number
  submittedCount: number
  gradedCount: number
  createdAt: string
}

export interface HomeworkSubmissionListItem {
  id: string
  assignmentId: string
  assignmentTitle: string
  studentName: string
  submittedAt: string | null
  score: number | null
  status: HomeworkSubmissionStatus
  isLate: boolean
}

export type HomeworkQuestionContent = { text?: string } & Record<string, unknown>

export type HomeworkSubmissionAnswerDetails = {
  id: string
  questionId: string
  questionContent: HomeworkQuestionContent | null
  questionType: string
  maxScore: number
  studentAnswer: unknown
  score: number | null
  feedback: string | null
  order: number
}

export type HomeworkSubmissionDetails = {
  id: string
  assignmentId: string
  assignmentTitle: string
  studentName: string
  submittedAt: string | null
  status: HomeworkSubmissionStatus
  totalScore: number | null
  answers: HomeworkSubmissionAnswerDetails[]
  prevSubmissionId?: string | null
  nextSubmissionId?: string | null
}

export type StudentHomeworkProgressStatus = "not_started" | "in_progress" | "submitted" | "graded"

export interface StudentHomeworkAssignmentListItem {
  id: string
  title: string
  subjectName?: string | null
  dueAt: string | null
  availableAt: string | null
  maxAttempts: number
  attemptsUsed: number
  progressStatus: StudentHomeworkProgressStatus
  latestSubmissionId: string | null
  latestSubmittedAt: string | null
  latestScore: number | null
}

export type StudentHomeworkPerformanceItem = {
  assignmentId: string
  title: string
  gradedAt: string
  score: number
  maxScore: number
  percent: number
  rank: number
  gradedCount: number
}

export type StudentHomeworkPerformanceSummary = {
  averagePercent: number | null
  bestPercent: number | null
  latestRank: { rank: number; gradedCount: number; percent: number } | null
}

export type StudentHomeworkTakeQuestion = {
  questionId: string
  questionType: string
  questionContent: HomeworkQuestionContent | null
  maxScore: number
  order: number
  savedAnswer: unknown
  score?: number | null
  feedback?: string | null
  knowledgePoints?: Array<{ id: string; name: string }>
}

export type StudentHomeworkTakeData = {
  assignment: {
    id: string
    title: string
    description: string | null
    availableAt: string | null
    dueAt: string | null
    allowLate: boolean
    lateDueAt: string | null
    maxAttempts: number
  }
  /**
   * 考试模式配置（仅当作业关联考试时存在）。
   * P0-竞品修复：限时/监考模式需在答题页展示倒计时并到时自动提交。
   */
  examModeConfig: {
    examMode: "homework" | "timed" | "proctored"
    durationMinutes: number | null
    shuffleQuestions: boolean
    allowLateStart: boolean
    lateStartGraceMinutes: number
    antiCheatEnabled: boolean
  } | null
  submission: {
    id: string
    status: HomeworkSubmissionStatus
    attemptNo: number
    submittedAt: string | null
    score: number | null
    /** 提交记录创建时间（用于计算限时考试的剩余时间） */
    startedAt: string | null
  } | null
  questions: StudentHomeworkTakeQuestion[]
}

export type HomeworkAssignmentQuestionAnalytics = {
  questionId: string
  questionType: string
  questionContent: HomeworkQuestionContent | null
  maxScore: number
  order: number
  errorCount: number
  errorRate: number
  wrongAnswers?: Array<{ studentId: string; studentName: string; answerContent: unknown; count?: number }>
}

export type HomeworkAssignmentAnalytics = {
  assignment: {
    id: string
    title: string
    description: string | null
    status: HomeworkAssignmentStatus
    sourceExamId: string | null
    sourceExamTitle: string | null
    structure: unknown | null
    availableAt: string | null
    dueAt: string | null
    allowLate: boolean
    lateDueAt: string | null
    maxAttempts: number
    targetCount: number
    submissionCount: number
    submittedCount: number
    gradedCount: number
    createdAt: string
    updatedAt: string
  }
  gradedSampleCount: number
  questions: HomeworkAssignmentQuestionAnalytics[]
}

export interface StudentHomeworkScoreAnalytics {
  assignmentId: string
  assignmentTitle: string
  score: number
  maxScore: number
  percentage: number
  submittedAt: string
}

export interface StudentRanking {
  studentId: string
  studentName: string
  rank: number
  classSize: number
  totalScore: number
  totalMaxScore: number
  percentage: number
}

export interface StudentDashboardGradeProps {
  trend: StudentHomeworkScoreAnalytics[]
  recent: StudentHomeworkScoreAnalytics[]
  ranking: StudentRanking | null
}

/**
 * 优秀作业展示项 —— 用于教师在作业详情页向学生展示班级优秀样例。
 *
 * 字段说明：
 * - `studentName` 仅展示姓名，不含 ID，保护隐私。
 * - `percentage` 用于排序与展示（0-100）。
 * - `isLate` 用于标注迟交但质量优秀的样例。
 * - `totalScore` / `maxScore` 用于展示实际分数。
 */
export interface ExcellentSubmissionItem {
  submissionId: string
  assignmentId: string
  assignmentTitle: string
  studentName: string
  totalScore: number
  maxScore: number
  percentage: number
  submittedAt: string
  isLate: boolean
}

/**
 * 优秀作业展示查询参数。
 *
 * - `assignmentId` 指定作业 ID（必填，按作业维度展示）。
 * - `minPercentage` 最低得分百分比阈值（默认 80，即 80%）。
 * - `limit` 返回数量上限（默认 10）。
 */
export interface ExcellentSubmissionQuery {
  assignmentId: string
  minPercentage?: number
  limit?: number
}

/**
 * 答题扫描图附件结构 —— 由 `getScansAction` 返回。
 *
 * 扫描图存储在 `fileAttachments` 表中，`targetType="homework"`、
 * `targetId=submissionId`。`page` 为按创建时间排序的页码（从 1 开始）。
 */
export interface ScanAttachment {
  fileId: string
  url: string
  filename: string
  originalName: string
  /** 页码（按创建时间排序，从 1 开始） */
  page: number
}

