"use client"

import type { UseFormReturn } from "react-hook-form"
import { toast } from "sonner"
import type { useTranslations } from "next-intl"
import type { usePreviewState } from "./use-exam-preview-state"
import type { ExamFormValues } from "../components/exam-form-types"
import { findPreviewQuestionNode, parseEditableContent } from "../components/exam-preview-utils"
import { regenerateAiQuestionAction } from "../actions"

type Translator = ReturnType<typeof useTranslations>

export function usePreviewRewrite(
  form: UseFormReturn<ExamFormValues>,
  t: Translator,
  state: ReturnType<typeof usePreviewState>,
) {
  const {
    previewNodes, selectedQuestionId, rewriteInstruction,
    setRewriteInstruction, setRewritingQuestion, updateSelectedQuestionFromAi,
  } = state

  const handleRewriteSelectedQuestion = async () => {
    if (!selectedQuestionId) {
      toast.error(t("exam.previewHook.selectQuestionFirst"))
      return
    }
    const selected = findPreviewQuestionNode(previewNodes, selectedQuestionId)
    if (!selected?.question) {
      toast.error(t("exam.previewHook.questionNotFound"))
      return
    }
    const instruction = rewriteInstruction.trim()
    if (!instruction) {
      toast.error(t("exam.previewHook.enterRewriteInstruction"))
      return
    }
    setRewritingQuestion(true)
    try {
      const content = parseEditableContent(selected.question.content)
      const questionPayload = {
        type: selected.question.type,
        difficulty: selected.question.difficulty ?? 3,
        score: selected.score ?? 0,
        content: {
          text: content.text,
          options: content.options.map((opt) => ({
            id: opt.id, text: opt.text, isCorrect: opt.isCorrect,
          })),
          subQuestions: content.subQuestions.map((item) => ({
            id: item.id, text: item.text, answer: item.answer, score: item.score,
          })),
        },
      }
      const formData = new FormData()
      formData.append("instruction", instruction)
      formData.append("questionJson", JSON.stringify(questionPayload))
      const providerId = form.getValues("aiProviderId")
      const sourceText = form.getValues("aiSourceText")
      if (providerId) formData.append("aiProviderId", providerId)
      if (sourceText) formData.append("sourceText", sourceText)
      const result = await regenerateAiQuestionAction(null, formData)
      if (!result.success || !result.data) {
        toast.error(result.message || t("exam.previewHook.aiRewriteFailed"))
        return
      }
      updateSelectedQuestionFromAi(selectedQuestionId, result.data)
      setRewriteInstruction("")
      toast.success(t("exam.previewHook.aiRewriteSuccess"))
    } catch (error) {
      console.error("[useExamPreview]", error instanceof Error ? error.message : String(error))
      toast.error(t("exam.previewHook.aiRewriteFailed"))
    } finally {
      setRewritingQuestion(false)
    }
  }

  return { handleRewriteSelectedQuestion }
}
