"use client"

import { useMemo, type ReactNode } from "react"
import { useTranslations } from "next-intl"
import { cn } from "@/shared/lib/utils"
import { Button } from "@/shared/components/ui/button"
import { ScrollArea } from "@/shared/components/ui/scroll-area"
import {
  Dialog,
  DialogContent,
  DialogTitle,
} from "@/shared/components/ui/dialog"
import type { ExamNode } from "./assembly/selected-question-list"
import type { EditableQuestionContent, PreviewSnapshotMeta } from "./exam-form-types"
import { ExamPreviewQuestionEditor } from "./exam-preview-question-editor"

type ExamPreviewDialogProps = {
  previewOpen: boolean
  setPreviewOpen: (open: boolean) => void
  previewLoading: boolean
  previewNodes: ExamNode[]
  previewTitle: string
  previewRawOutput: string
  previewMeta: PreviewSnapshotMeta | null
  selectedQuestionId: string
  setSelectedQuestionId: (id: string) => void
  rewriteInstruction: string
  setRewriteInstruction: (value: string) => void
  rewritingQuestion: boolean
  previewQuestionRows: Array<{ node: ExamNode; sectionTitle?: string }>
  selectedPreviewQuestion: ExamNode | null
  selectedPreviewContent: EditableQuestionContent | null
  activePreviewMeta: PreviewSnapshotMeta
  updatePreviewQuestionNode: (questionId: string, updater: (node: ExamNode) => ExamNode) => void
  parseEditableContent: (raw: unknown) => EditableQuestionContent
  handleRewriteSelectedQuestion: () => void
  handleConfirmCreate: () => void
  previewTitleValue?: string
}

// 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 && node.questionId) {
        counter += 1
        map.set(node.id, counter)
      } else if (node.type === "group" && node.children) {
        walk(node.children)
      }
    }
  }
  walk(nodes)
  return map
}

export function ExamPreviewDialog({
  previewOpen,
  setPreviewOpen,
  previewLoading,
  previewNodes,
  previewTitle,
  previewRawOutput,
  selectedQuestionId,
  setSelectedQuestionId,
  rewriteInstruction,
  setRewriteInstruction,
  rewritingQuestion,
  previewQuestionRows,
  selectedPreviewQuestion,
  selectedPreviewContent,
  activePreviewMeta,
  updatePreviewQuestionNode,
  parseEditableContent,
  handleRewriteSelectedQuestion,
  handleConfirmCreate,
  previewTitleValue,
}: ExamPreviewDialogProps) {
  // Stable numbering map - recomputed only when nodes change. Avoids StrictMode double-increment.
  const numberMap = useMemo(() => buildQuestionNumberMap(previewNodes), [previewNodes])
  const t = useTranslations("examHomework")

  const renderSelectablePreview = (nodes: ExamNode[]) => {
    const renderNode = (node: ExamNode, depth: number = 0): ReactNode => {
      if (node.type === "group") {
        return (
          <div key={node.id} className="space-y-3 mb-6">
            <h3 className={cn("font-semibold text-foreground/90", depth === 0 ? "text-base" : "text-sm")}>
              {node.title || t("exam.previewDialog.section")}
            </h3>
            <div className="space-y-3">
              {(node.children ?? []).map((child) => renderNode(child, depth + 1))}
            </div>
          </div>
        )
      }
      if (node.type === "question" && node.question && node.questionId) {
        const questionNumber = numberMap.get(node.id) ?? 0
        const content = parseEditableContent(node.question.content)
        const active = node.questionId === selectedQuestionId
        return (
          <button
            key={node.id}
            type="button"
            onClick={() => setSelectedQuestionId(node.questionId ?? "")}
            className={cn(
              "w-full rounded-md border p-3 text-left transition-colors",
              active ? "border-primary bg-primary/5" : "border-border hover:bg-accent"
            )}
          >
            <div className="flex gap-2">
              <span className="font-semibold text-foreground min-w-[28px]">{questionNumber}.</span>
              <div className="flex-1 space-y-2">
                <div className="text-foreground/90 leading-relaxed whitespace-pre-wrap">
                  {content.text || t("exam.previewDialog.untitledQuestion")}
                  <span className="text-muted-foreground text-xs ml-2">({node.score ?? 0}{t("exam.previewDialog.scoreUnit")})</span>
                </div>
                {content.options.length > 0 ? (
                  <div className="space-y-1.5">
                    {content.options.map((opt) => (
                      <div key={`${node.id}-${opt.id}`} className="text-sm text-foreground/80 flex gap-2">
                        <span className="min-w-[28px]">{opt.id}.</span>
                        <span className="whitespace-pre-wrap">{opt.text}</span>
                      </div>
                    ))}
                  </div>
                ) : null}
                {content.subQuestions.length > 0 ? (
                  <div className="space-y-1.5 rounded-md bg-muted/40 p-2">
                    {content.subQuestions.map((item, index) => (
                      <div key={`${node.id}-sub-${index}`} className="text-sm text-foreground/80 flex gap-2">
                        <span className="min-w-[28px]">{item.id}.</span>
                        <span className="whitespace-pre-wrap">{item.text || t("exam.previewDialog.untitledSubQuestion")}</span>
                        {item.score ? <span className="text-xs text-muted-foreground">({item.score}{t("exam.previewDialog.scoreUnit")})</span> : null}
                      </div>
                    ))}
                  </div>
                ) : null}
              </div>
            </div>
          </button>
        )
      }
      return null
    }
    return (
      <div className="space-y-2">
        {nodes.map((node) => renderNode(node))}
      </div>
    )
  }

  return (
    <Dialog open={previewOpen} onOpenChange={setPreviewOpen}>
      <DialogContent className="max-w-7xl h-[90vh] flex flex-col p-0 gap-0">
        <div className="p-4 border-b shrink-0 flex items-center justify-between">
          <DialogTitle className="text-lg font-semibold tracking-tight">
            {previewTitle || previewTitleValue || t("exam.previewDialog.title")}
          </DialogTitle>
        </div>
        {previewLoading ? (
          <div className="flex-1 py-20 text-center text-muted-foreground">{t("exam.previewDialog.generating")}</div>
        ) : previewNodes.length > 0 ? (
          <div className="flex-1 grid grid-cols-12 min-h-0">
            <div className="col-span-5 border-r min-h-0 flex flex-col">
              <div className="p-4 border-b">
                <div className="text-sm font-medium">{t("exam.previewDialog.fullPreview")}</div>
                <div className="text-xs text-muted-foreground mt-1">
                  {t("exam.previewDialog.summary", {
                    count: previewQuestionRows.length,
                    subject: activePreviewMeta.subject,
                    grade: activePreviewMeta.grade,
                    minutes: activePreviewMeta.durationMin,
                    total: activePreviewMeta.totalScore,
                  })}
                </div>
              </div>
              <ScrollArea className="flex-1">
                <div className="p-4">
                  {renderSelectablePreview(previewNodes)}
                </div>
              </ScrollArea>
            </div>

            <div className="col-span-7 min-h-0 flex flex-col">
              <ExamPreviewQuestionEditor
                selectedQuestion={selectedPreviewQuestion}
                selectedContent={selectedPreviewContent}
                selectedQuestionId={selectedQuestionId}
                updatePreviewQuestionNode={updatePreviewQuestionNode}
                parseEditableContent={parseEditableContent}
                rewriteInstruction={rewriteInstruction}
                setRewriteInstruction={setRewriteInstruction}
                rewritingQuestion={rewritingQuestion}
                handleRewriteSelectedQuestion={handleRewriteSelectedQuestion}
                previewRawOutput={previewRawOutput}
              />
            </div>
          </div>
        ) : (
          <div className="flex-1 py-20 text-center text-muted-foreground">{t("exam.previewDialog.noPreview")}</div>
        )}
        <div className="border-t p-4 flex justify-end">
          <Button type="button" disabled={previewLoading || previewNodes.length === 0} onClick={handleConfirmCreate}>
            {t("exam.previewDialog.confirmCreate")}
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  )
}
