"use client"

import { useState } from "react"
import type { AiPreviewData, AiRewriteQuestionData } from "../actions"
import type { ExamNode } from "../components/assembly/selected-question-list"
import type { ExamFormValues, PreviewSnapshotMeta } from "../components/exam-form-types"
import {
  buildPreviewNodes,
  flattenPreviewQuestions,
  updatePreviewQuestionNodeInList,
} from "../components/exam-preview-utils"

export function usePreviewState() {
  const [previewOpen, setPreviewOpen] = useState(false)
  const [previewLoading, setPreviewLoading] = useState(false)
  const [previewNodes, setPreviewNodes] = useState<ExamNode[]>([])
  const [previewTitle, setPreviewTitle] = useState("")
  const [previewRawOutput, setPreviewRawOutput] = useState("")
  const [previewSignature, setPreviewSignature] = useState("")
  const [previewMeta, setPreviewMeta] = useState<PreviewSnapshotMeta | null>(null)
  const [selectedQuestionId, setSelectedQuestionId] = useState<string>("")
  const [rewriteInstruction, setRewriteInstruction] = useState("")
  const [rewritingQuestion, setRewritingQuestion] = useState(false)

  const updatePreviewQuestionNode = (questionId: string, updater: (node: ExamNode) => ExamNode) => {
    setPreviewNodes((prev) => updatePreviewQuestionNodeInList(questionId, prev, updater))
  }

  const updateSelectedQuestionFromAi = (questionId: string, data: AiRewriteQuestionData) => {
    updatePreviewQuestionNode(questionId, (node) => {
      if (!node.question) return node
      return {
        ...node,
        score: data.score,
        question: {
          ...node.question,
          type: data.type,
          difficulty: data.difficulty,
          content: data.content,
          updatedAt: new Date(),
        },
      }
    })
  }

  const applyPreviewResult = (input: { data: AiPreviewData; signature: string; meta: PreviewSnapshotMeta }) => {
    setPreviewTitle(input.data.title)
    const nextNodes = buildPreviewNodes(input.data)
    setPreviewNodes(nextNodes)
    const firstQuestion = flattenPreviewQuestions(nextNodes)[0]
    setSelectedQuestionId(firstQuestion?.node.questionId ?? "")
    setPreviewRawOutput(input.data.rawOutput ?? "")
    setPreviewSignature(input.signature)
    setPreviewMeta(input.meta)
    setRewriteInstruction("")
    setPreviewOpen(true)
  }

  return {
    previewOpen, setPreviewOpen, previewLoading, setPreviewLoading,
    previewNodes, setPreviewNodes, previewTitle, setPreviewTitle,
    previewRawOutput, setPreviewRawOutput, previewSignature, setPreviewSignature,
    previewMeta, setPreviewMeta, selectedQuestionId, setSelectedQuestionId,
    rewriteInstruction, setRewriteInstruction, rewritingQuestion, setRewritingQuestion,
    updatePreviewQuestionNode, updateSelectedQuestionFromAi, applyPreviewResult,
  }
}
