"use client"

import { toast } from "sonner"
import type { useTranslations } from "next-intl"
import type { UseFormReturn } from "react-hook-form"

import { previewAiExamAction } from "../actions"
import type { ExamFormValues } from "../components/exam-form-types"
import {
  buildPreviewNodes,
  buildPreviewPayload,
  buildPreviewRequestData,
  buildPreviewSignature,
  findPreviewQuestionNode,
  flattenPreviewQuestions,
  parseEditableContent,
} from "../components/exam-preview-utils"
import { usePreviewState } from "./use-exam-preview-state"
import { usePreviewBackgroundTasks } from "./use-exam-preview-tasks"
import { usePreviewRewrite } from "./use-exam-preview-rewrite"

export type Translator = ReturnType<typeof useTranslations>

export function useExamPreview(form: UseFormReturn<ExamFormValues>, t: Translator) {
  const state = usePreviewState()
  const tasks = usePreviewBackgroundTasks(form, t, state)
  const rewrite = usePreviewRewrite(form, t, state)
  const {
    setPreviewOpen, setPreviewLoading, setPreviewNodes, setPreviewRawOutput,
    setPreviewSignature, setSelectedQuestionId, setRewriteInstruction, applyPreviewResult,
  } = state

  const handlePreview = async () => {
    const values = form.getValues()
    const requestData = buildPreviewRequestData(values)
    if (!requestData) {
      toast.error(t("exam.previewHook.pasteSourceFirst"))
      return
    }
    setPreviewOpen(false)
    setPreviewLoading(true)
    setPreviewNodes([])
    setPreviewRawOutput("")
    setPreviewSignature("")
    setSelectedQuestionId("")
    setRewriteInstruction("")
    try {
      const result = await previewAiExamAction(null, requestData.formData)
      if (result.success && result.data) {
        applyPreviewResult({ data: result.data, signature: requestData.signature, meta: requestData.meta })
      } else {
        toast.error(result.message || t("exam.previewHook.generatePreviewFailed"))
      }
    } catch (error) {
      console.error("[useExamPreview]", error instanceof Error ? error.message : String(error))
      toast.error(t("exam.previewHook.generatePreviewFailed"))
    } finally {
      setPreviewLoading(false)
    }
  }

  return {
    ...state, ...tasks, ...rewrite,
    buildPreviewNodes, parseEditableContent, flattenPreviewQuestions,
    findPreviewQuestionNode, buildPreviewPayload, buildPreviewRequestData,
    buildPreviewSignature, handlePreview,
  }
}
