"use client"

import { useEffect, useRef, useState } from "react"
import type { UseFormReturn } from "react-hook-form"
import { toast } from "sonner"
import PQueue from "p-queue"
import { createId } from "@paralleldrive/cuid2"
import type { useTranslations } from "next-intl"
import type { usePreviewState } from "./use-exam-preview-state"
import { type ExamFormValues, type PreviewBackgroundTask, previewTaskStorageKey } from "../components/exam-form-types"
import {
  buildPreviewRequestData,
  executeBackgroundPreviewTask,
  flattenPreviewQuestions,
  parseStoredPreviewTasks,
  persistPreviewTasksToStorage,
} from "../components/exam-preview-utils"

type Translator = ReturnType<typeof useTranslations>

export function usePreviewBackgroundTasks(
  form: UseFormReturn<ExamFormValues>,
  t: Translator,
  state: ReturnType<typeof usePreviewState>,
) {
  const [previewTasks, setPreviewTasks] = useState<PreviewBackgroundTask[]>([])
  const previewQueueRef = useRef<PQueue | null>(null)
  if (!previewQueueRef.current) previewQueueRef.current = new PQueue({ concurrency: 3 })
  const previewQueue = previewQueueRef.current

  useEffect(() => {
    try {
      const raw = window.localStorage.getItem(previewTaskStorageKey)
      const restoredTasks = raw ? parseStoredPreviewTasks(raw, t) : null
      if (!restoredTasks) return
      setPreviewTasks(restoredTasks)
      if (restoredTasks.length > 0) form.setValue("mode", "ai")
    } catch (error) {
      console.error("[useExamPreview]", error instanceof Error ? error.message : String(error))
      setPreviewTasks([])
    }
  }, [form])

  useEffect(() => () => { previewQueue.clear() }, [previewQueue])
  useEffect(() => { persistPreviewTasksToStorage(previewTasks) }, [previewTasks])

  const handleBackgroundPreview = () => {
    const values = form.getValues()
    const requestData = buildPreviewRequestData(values)
    if (!requestData) { toast.error(t("exam.previewHook.pasteSourceFirst")); return }
    const taskId = createId()
    const taskTitle = values.title?.trim() || t("exam.previewHook.untitledExam")
    setPreviewTasks((prev) => {
      const next = [{ id: taskId, createdAt: Date.now(), status: "queued" as const, title: taskTitle, signature: requestData.signature }, ...prev]
      persistPreviewTasksToStorage(next)
      return next
    })
    toast.success(t("exam.previewHook.queuedSuccess"))
    void previewQueue.add(() => executeBackgroundPreviewTask(taskId, taskTitle, values, requestData, t, setPreviewTasks))
  }

  const handleOpenPreviewTask = (taskId: string) => {
    const task = previewTasks.find((item) => item.id === taskId)
    if (!task || task.status !== "success" || !task.result) return
    const tv = task.result.formValues
    const fields = ["title", "subject", "grade", "difficulty", "totalScore", "durationMin", "aiSourceText", "aiQuestionCount", "aiProviderId"] as const
    fields.forEach((key) => { if (typeof tv[key] !== "undefined") form.setValue(key, tv[key]) })
    state.setPreviewTitle(task.result.title)
    state.setPreviewNodes(task.result.nodes)
    state.setPreviewRawOutput(task.result.rawOutput)
    state.setPreviewSignature(task.signature)
    state.setPreviewMeta(task.result.meta)
    const firstQuestion = flattenPreviewQuestions(task.result.nodes)[0]
    state.setSelectedQuestionId(firstQuestion?.node.questionId ?? "")
    state.setRewriteInstruction("")
    state.setPreviewOpen(true)
  }

  return { previewTasks, setPreviewTasks, handleBackgroundPreview, handleOpenPreviewTask }
}
