"use client"

import type { ReactNode } from "react"
import Image from "next/image"
import { useTranslations } from "next-intl"
import { cn } from "@/shared/lib/utils"
import type { EditorDoc } from "../editor"

/**
 * 试卷预览组件
 *
 * 从 exam-rich-form.tsx 提取，负责渲染试卷结构预览。
 * 支持分卷(section)、大题分组(group)、题目(question)三级嵌套。
 */
export function ExamPreview({ structure }: { structure: EditorDoc }): ReactNode {
  const t = useTranslations("examHomework")
  const counter = { value: 0 }

  const renderNode = (
    node: EditorDoc["structure"][number],
    depth: number = 0
  ): ReactNode => {
    // 分卷(第Ⅰ卷)—— 顶层结构,显示标题 + 自动统计
    if (node.type === "section") {
      const level = node.level ?? 1
      return (
        <div key={node.id} className="mb-6">
          <div className="mb-3 flex items-baseline gap-3 border-b-2 border-foreground pb-2">
            <h2 className={cn("font-bold", level === 1 ? "text-lg" : "text-base")}>
              {node.title || (level === 1 ? t("exam.richForm.sectionLabel") : t("exam.richForm.partLabel"))}
            </h2>
            {node.questionCount !== undefined && node.totalScore !== undefined && (
              <span className="text-xs text-muted-foreground">
                {t("exam.richForm.questionCountSummary", { count: node.questionCount, score: node.totalScore })}
              </span>
            )}
          </div>
          <div className="space-y-4">
            {(node.children ?? []).map((child) => renderNode(child, depth + 1))}
          </div>
        </div>
      )
    }

    // 大题分组(一、选择题)—— 显示标题 + 说明 + 自动统计
    if (node.type === "group") {
      return (
        <div key={node.id} className="mb-5">
          <div className="mb-2 flex items-baseline gap-2 border-b border-foreground/30 pb-1">
            <h3 className="text-base font-bold text-foreground">
              {node.title || t("exam.richForm.groupLabel")}
            </h3>
            {node.questionCount !== undefined && node.totalScore !== undefined && (
              <span className="text-xs text-muted-foreground">
                {t("exam.richForm.questionCountSummary", { count: node.questionCount, score: node.totalScore })}
              </span>
            )}
          </div>
          {node.instruction && (
            <p className="mb-2 text-xs text-muted-foreground italic">
              {node.instruction}
            </p>
          )}
          <div className="space-y-3 pl-2">
            {(node.children ?? []).map((child) => renderNode(child, depth + 1))}
          </div>
        </div>
      )
    }

    // 题目
    const question = structure.questions.find((q) => q.id === node.questionId)
    if (!question) return null
    counter.value += 1
    const qNum = counter.value
    const isComposite = question.type === "composite"
    const typeLabel = question.type === "single_choice" ? t("exam.richForm.typeSingleChoice")
      : question.type === "multiple_choice" ? t("exam.richForm.typeMultipleChoice")
      : question.type === "judgment" ? t("exam.richForm.typeJudgment")
      : question.type === "composite" ? t("exam.richForm.typeComposite")
      : t("exam.richForm.typeShortAnswer")

    return (
      <div key={node.id} className="rounded border border-border/60 bg-background p-3">
        {/* 题目头部:题号 + 题型标签 + 分值 */}
        <div className="flex items-center gap-2 mb-2">
          <span className="font-bold text-foreground min-w-[32px]">{qNum}.</span>
          <span className="rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground">
            {typeLabel}
          </span>
          <span className="ml-auto text-xs text-muted-foreground">
            {question.score} {t("exam.richForm.scoreUnit")}
          </span>
        </div>
        {/* 题干文本 */}
        {question.content.text && (
          <div className="mb-2 text-sm text-foreground/90 leading-relaxed whitespace-pre-wrap pl-8">
            {question.content.text}
          </div>
        )}
        {/* 选项 */}
        {question.content.options && question.content.options.length > 0 && (
          <div className="space-y-1.5 pl-8 mb-2">
            {question.content.options.map((opt) => (
              <div
                key={`${question.id}-${opt.id}`}
                className="text-sm text-foreground/80 flex gap-2"
              >
                <span className="font-medium min-w-[20px]">{opt.id}.</span>
                <span>{opt.text}</span>
              </div>
            ))}
          </div>
        )}
        {/* 复合题子题(阅读理解小题) */}
        {isComposite && question.content.subQuestions && question.content.subQuestions.length > 0 && (
          <div className="mt-3 ml-4 space-y-3 border-l-2 border-primary/30 pl-4">
            {question.content.subQuestions.map((sub, idx) => (
              <div key={`${question.id}-sub-${sub.id}`} className="text-sm">
                <div className="flex items-center gap-2 mb-1">
                  <span className="font-medium text-foreground/80">
                    ({idx + 1})
                  </span>
                  {sub.score !== undefined && (
                    <span className="text-xs text-muted-foreground">
                      {sub.score} {t("exam.richForm.scoreUnit")}
                    </span>
                  )}
                </div>
                <div className="text-foreground/80 whitespace-pre-wrap pl-6">
                  {sub.text}
                </div>
              </div>
            ))}
          </div>
        )}
        {/* 图片 */}
        {question.content.images && question.content.images.length > 0 && (
          <div className="mt-2 pl-8 flex flex-wrap gap-2">
            {question.content.images.map((img) => (
              <div
                key={img.fileId}
                className="relative h-32 w-32 overflow-hidden rounded border"
              >
                <Image
                  src={img.url}
                  alt={img.alt || ""}
                  fill
                  sizes="128px"
                  className="h-full w-full object-contain"
                />
              </div>
            ))}
          </div>
        )}
      </div>
    )
  }

  return (
    <div className="space-y-4">
      {structure.title && (
        <h2 className="text-center text-lg font-bold border-b pb-2">
          {structure.title}
        </h2>
      )}
      {structure.structure.length === 0 ? (
        <p className="text-center text-sm text-muted-foreground py-8">
          {t("exam.richForm.emptyPreview")}
        </p>
      ) : (
        structure.structure.map((node) => renderNode(node))
      )}
    </div>
  )
}
