"use client"

import { useMemo } from "react"
import { useTranslations } from "next-intl"
import type { ExamNode } from "./selected-question-list"

type ChoiceOption = {
  id: string
  text: string
}

type QuestionContent = {
  text?: string
  options?: ChoiceOption[]
}

type ExamPaperPreviewProps = {
  title: string
  subject: string
  grade: string
  durationMin: number
  totalScore: number
  nodes: ExamNode[]
}

const parseContent = (raw: unknown): QuestionContent => {
  if (raw && typeof raw === "object") return raw as QuestionContent
  if (typeof raw === "string") {
    try {
      const parsed = JSON.parse(raw) as unknown
      if (parsed && typeof parsed === "object") return parsed as QuestionContent
      return { text: raw }
    } catch {
      return { text: raw }
    }
  }
  return {}
}

// Precompute question numbers as a Map to avoid mutating a counter during render
const buildQuestionNumberMap = (nodes: ExamNode[]): Map<string, number> => {
  const map = new Map<string, number>()
  let counter = 0
  const walk = (list: ExamNode[]) => {
    for (const node of list) {
      if (node.type === "question" && node.question) {
        counter += 1
        map.set(node.id, counter)
      } else if ((node.type === "group" || node.type === "section") && node.children) {
        walk(node.children)
      }
    }
  }
  walk(nodes)
  return map
}

export function ExamPaperPreview({ title, subject, grade, durationMin, totalScore, nodes }: ExamPaperPreviewProps) {
  const t = useTranslations("examHomework.exam.build")
  const tPaper = useTranslations("examHomework.exam.paperPreview")
  // Stable numbering map - recomputed only when nodes change. Avoids StrictMode double-increment.
  const numberMap = useMemo(() => buildQuestionNumberMap(nodes), [nodes])

  const renderNode = (node: ExamNode, depth: number = 0) => {
    if (node.type === 'section') {
      return (
        <div key={node.id} className="space-y-4 mb-8">
          <div className="flex items-baseline gap-3 border-b-2 border-foreground pb-2">
            <h2 className={`font-bold ${depth === 0 ? 'text-xl' : 'text-lg'} text-foreground`}>
              {node.title || t("section")}
            </h2>
          </div>
          <div className="pl-0">
            {node.children?.map(child => renderNode(child, depth + 1))}
          </div>
        </div>
      )
    }

    if (node.type === 'group') {
      return (
        <div key={node.id} className="space-y-4 mb-6">
          <div className="flex items-center gap-2">
            <h3 className={`font-bold ${depth === 0 ? 'text-lg' : 'text-md'} text-foreground/90`}>
              {node.title || t("group")}
            </h3>
            {node.instruction && (
              <span className="text-xs text-muted-foreground italic">{node.instruction}</span>
            )}
          </div>
          <div className="pl-0">
            {node.children?.map(child => renderNode(child, depth + 1))}
          </div>
        </div>
      )
    }

    if (node.type === 'question' && node.question) {
      const questionNumber = numberMap.get(node.id) ?? 0
      const q = node.question
      const content = parseContent(q.content)

      return (
        <div key={node.id} className="mb-6 break-inside-avoid">
          <div className="flex gap-2">
            <span className="font-semibold text-foreground min-w-[24px]">{questionNumber}.</span>
            <div className="flex-1 space-y-2">
              <div className="text-foreground/90 leading-relaxed whitespace-pre-wrap">
                {content.text ?? ""}
                <span className="text-muted-foreground text-sm ml-2">{tPaper("scoreWithUnit", { score: node.score ?? 0 })}</span>
              </div>

              {/* Options for Choice Questions */}
              {(q.type === 'single_choice' || q.type === 'multiple_choice') && content.options && (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-y-2 gap-x-4 mt-2 pl-2">
                  {content.options.map((opt) => (
                    <div key={opt.id} className="flex gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors">
                      <span className="font-medium">{opt.id}.</span>
                      <span>{opt.text}</span>
                    </div>
                  ))}
                </div>
              )}

              {/* Space for written answers */}
              {q.type === 'text' && (
                <div className="mt-4 h-24 border-b border-dashed border-muted-foreground/30 w-full"></div>
              )}
            </div>
          </div>
        </div>
      )
    }
    return null
  }

  return (
    <div className="bg-card shadow-sm border p-12 print:shadow-none print:border-none">
      {/* Header */}
      <div className="text-center space-y-4 mb-12 border-b-2 border-primary/20 pb-8">
        <h1 className="text-3xl font-black tracking-tight text-foreground">{title}</h1>
        <div className="flex justify-center gap-8 text-sm text-muted-foreground font-medium uppercase tracking-wide">
          <span>{t("previewSubject")}: {subject}</span>
          <span>{t("previewGrade")}: {grade}</span>
          <span>{t("previewTime")}: {durationMin} {t("minutes")}</span>
          <span>{t("previewTotal")}: {totalScore} {t("pts")}</span>
        </div>
        <div className="flex justify-center gap-12 text-sm pt-4">
          <div className="w-32 border-b border-foreground/20 text-left px-1">{t("previewClass")}:</div>
          <div className="w-32 border-b border-foreground/20 text-left px-1">{t("previewName")}:</div>
          <div className="w-32 border-b border-foreground/20 text-left px-1">{t("previewNo")}:</div>
        </div>
      </div>

      {/* Content */}
      <div className="space-y-2">
        {nodes.length === 0 ? (
          <div className="text-center py-20 text-muted-foreground">
            {t("emptyExamPaper")}
          </div>
        ) : (
          nodes.map(node => renderNode(node))
        )}
      </div>
    </div>
  )
}
