"use client"

import type { ReactNode } from "react"
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
}

export function ExamPreviewDialog({
  previewOpen,
  setPreviewOpen,
  previewLoading,
  previewNodes,
  previewTitle,
  previewRawOutput,
  selectedQuestionId,
  setSelectedQuestionId,
  rewriteInstruction,
  setRewriteInstruction,
  rewritingQuestion,
  previewQuestionRows,
  selectedPreviewQuestion,
  selectedPreviewContent,
  activePreviewMeta,
  updatePreviewQuestionNode,
  parseEditableContent,
  handleRewriteSelectedQuestion,
  handleConfirmCreate,
  previewTitleValue,
}: ExamPreviewDialogProps) {
  const renderSelectablePreview = (nodes: ExamNode[]) => {
    let questionCounter = 0
    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 || "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) {
        questionCounter += 1
        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]">{questionCounter}.</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-xs ml-2">({node.score ?? 0}分)</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 || "未命名子题"}</span>
                        {item.score ? <span className="text-xs text-muted-foreground">({item.score}分)</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 || "Exam Preview"}
          </DialogTitle>
        </div>
        {previewLoading ? (
          <div className="flex-1 py-20 text-center text-muted-foreground">Generating preview...</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">完整试卷预览</div>
                <div className="text-xs text-muted-foreground mt-1">
                  {previewQuestionRows.length} 题 · 科目 {activePreviewMeta.subject} · 年级 {activePreviewMeta.grade} · {activePreviewMeta.durationMin} 分钟 · 总分 {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">No preview available</div>
        )}
        <div className="border-t p-4 flex justify-end">
          <Button type="button" disabled={previewLoading || previewNodes.length === 0} onClick={handleConfirmCreate}>
            Confirm & Create
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  )
}
