"use client"

import { useTranslations } from "next-intl"
import { Check, CloudOff, CloudUpload, Loader2, TriangleAlert } from "lucide-react"

import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { Label } from "@/shared/components/ui/label"
import { cn, formatDate } from "@/shared/lib/utils"

import type { StudentHomeworkTakeData } from "../types"

type AutoSaveStatus = "idle" | "saving" | "saved" | "error"

type AnswersByQuestionId = Record<string, { answer: unknown }>

type HomeworkTakeSidebarProps = {
  assignment: StudentHomeworkTakeData["assignment"]
  questions: StudentHomeworkTakeData["questions"]
  answersByQuestionId: AnswersByQuestionId
  submissionStatus: string
  canEdit: boolean
  isBusy: boolean
  showQuestions: boolean
  autoSaveStatus: AutoSaveStatus
  dueAt: string | null
  isOverdue: boolean
  isUrgent: boolean
  hoursUntilDue: number | null
  maxAttempts: number
  attemptsUsed: number
  attemptsRemaining: number
  onSubmitClick: () => void
  onQuestionJump: (questionId: string, index: number) => void
}

/**
 * 学生作答页 —— 右侧信息侧边栏。
 *
 * 展示：自动保存状态、作业状态、截止时间（含逾期/紧急高亮）、
 * 尝试次数、作业描述、答题进度（题号网格点击跳转）、提交按钮。
 */
export function HomeworkTakeSidebar({
  assignment,
  questions,
  answersByQuestionId,
  submissionStatus,
  canEdit,
  isBusy,
  showQuestions,
  autoSaveStatus,
  dueAt,
  isOverdue,
  isUrgent,
  hoursUntilDue,
  maxAttempts,
  attemptsUsed,
  attemptsRemaining,
  onSubmitClick,
  onQuestionJump,
}: HomeworkTakeSidebarProps) {
  const t = useTranslations("examHomework")

  return (
    <div className="lg:col-span-3 flex flex-col h-full overflow-hidden rounded-md border bg-card">
      <div className="border-b p-4 bg-muted/30">
        <h3 className="font-semibold">{t("homework.take.assignmentInfo")}</h3>
        {canEdit && (
          <div className="mt-2 flex items-center gap-1.5 text-xs text-muted-foreground" role="status" aria-live="polite">
            {autoSaveStatus === "saving" && <Loader2 className="h-3 w-3 animate-spin" />}
            {autoSaveStatus === "saved" && <Check className="h-3 w-3 text-green-500" />}
            {autoSaveStatus === "error" && <CloudOff className="h-3 w-3 text-destructive" />}
            {autoSaveStatus === "idle" && <CloudUpload className="h-3 w-3" />}
            <span className={
              autoSaveStatus === "saved" ? "text-green-600" :
              autoSaveStatus === "error" ? "text-destructive" :
              "text-muted-foreground"
            }>
              {t(`homework.take.autoSave${autoSaveStatus.charAt(0).toUpperCase()}${autoSaveStatus.slice(1)}`)}
            </span>
          </div>
        )}
      </div>
      <div className="flex-1 p-4 overflow-y-auto">
        <div className="space-y-6">
          <div>
            <Label className="text-xs text-muted-foreground uppercase tracking-wider">{t("homework.take.status")}</Label>
            <div className="mt-1 flex items-center gap-2">
              <Badge variant={submissionStatus === "started" ? "default" : "outline"} className="capitalize">
                {submissionStatus === "not_started" ? t("homework.take.notStarted") : submissionStatus}
              </Badge>
            </div>
          </div>

          {dueAt && (
            <div>
              <Label className="text-xs text-muted-foreground uppercase tracking-wider">{t("homework.take.dueDate")}</Label>
              <div className={cn(
                "mt-1 flex items-center gap-2 text-sm font-medium",
                isOverdue ? "text-destructive" : isUrgent ? "text-orange-500" : "text-foreground"
              )}>
                {(isOverdue || isUrgent) && <TriangleAlert className="h-4 w-4" />}
                <span>{formatDate(dueAt)}</span>
              </div>
              {isOverdue && (
                <p className="mt-1 text-xs text-destructive">{t("homework.take.overdue")}</p>
              )}
              {isUrgent && !isOverdue && hoursUntilDue !== null && (
                <p className="mt-1 text-xs text-orange-500">
                  {hoursUntilDue === 0
                    ? t("homework.take.lessThanOneHour")
                    : t("homework.take.hoursLeft", { hours: hoursUntilDue })}
                </p>
              )}
            </div>
          )}

          {maxAttempts > 0 && (
            <div>
              <Label className="text-xs text-muted-foreground uppercase tracking-wider">{t("homework.take.attempts")}</Label>
              <div className="mt-1 text-sm">
                <span className="font-medium">{attemptsUsed}</span>
                <span className="text-muted-foreground"> {t("homework.take.attemptsUsed", { used: attemptsUsed, max: maxAttempts })}</span>
                {attemptsRemaining > 0 && (
                  <span className="text-muted-foreground"> {t("homework.take.attemptsRemaining", { remaining: attemptsRemaining })}</span>
                )}
              </div>
            </div>
          )}

          <div>
            <Label className="text-xs text-muted-foreground uppercase tracking-wider">{t("homework.take.description")}</Label>
            <p className="mt-1 text-sm text-muted-foreground leading-relaxed">
              {assignment.description || t("homework.take.noDescription")}
            </p>
          </div>

          {showQuestions && (
            <div>
              <Label className="text-xs text-muted-foreground uppercase tracking-wider">{t("homework.take.progress")}</Label>
              <div className="mt-2 grid grid-cols-5 gap-2">
                {questions.map((q, i) => {
                  const answer = answersByQuestionId[q.questionId]?.answer
                  const hasAnswer = answer !== undefined &&
                                  answer !== "" &&
                                  (Array.isArray(answer) ? answer.length > 0 : true)

                  return (
                    <button
                      key={q.questionId}
                      type="button"
                      onClick={() => onQuestionJump(q.questionId, i)}
                      className={cn(
                        "h-11 w-11 sm:h-8 sm:w-8 rounded flex items-center justify-center text-xs font-medium border transition-colors hover:opacity-80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1",
                        hasAnswer ? "bg-primary text-primary-foreground border-primary" : "bg-background text-muted-foreground border-input"
                      )}
                      aria-label={t("homework.take.jumpToQuestion", { index: i + 1 })}
                      aria-pressed={hasAnswer}
                      title={hasAnswer ? t("homework.take.answered") : t("homework.take.unanswered")}
                    >
                      {i + 1}
                    </button>
                  )
                })}
              </div>
            </div>
          )}
        </div>
      </div>

      {canEdit && (
        <div className="border-t p-4 bg-muted/20">
          <Button className="w-full" onClick={onSubmitClick} disabled={isBusy}>
            {isBusy ? t("homework.take.submitting") : t("homework.take.submitAll")}
          </Button>
          <p className="mt-2 text-xs text-center text-muted-foreground">
            {t("homework.take.makeSureAnswered")}
          </p>
        </div>
      )}
    </div>
  )
}
