"use client"

import { useTransition, useEffect, useState, type FormEvent } from "react"
import { useRouter } from "next/navigation"
import { useTranslations } from "next-intl"
import { useForm, type Resolver } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { toast } from "sonner"

import { Form } from "@/shared/components/ui/form"
import { createAiExamAction, createExamAction, getSubjectsAction, getGradesAction } from "../actions"
import { getAiProviderSummaries, type AiProviderSummary } from "@/modules/settings/actions"

import { formSchema, type ExamFormValues, type PreviewSnapshotMeta, defaultValues } from "./exam-form-types"
import { useExamPreview } from "../hooks/use-exam-preview"
import { ExamBasicInfoForm } from "./exam-basic-info-form"
import { ExamAiGenerator } from "./exam-ai-generator"
import { ExamPreviewDialog } from "./exam-preview-dialog"
import { ExamModeSelector } from "./exam-mode-selector"
import { ExamModeConfig } from "@/modules/proctoring/components/exam-mode-config"

// Re-export formSchema for backward compatibility
export { formSchema } from "./exam-form-types"
export type { ExamFormValues } from "./exam-form-types"

export function ExamForm() {
  const router = useRouter()
  const t = useTranslations("examHomework")
  const [isPending, startTransition] = useTransition()
  const [subjects, setSubjects] = useState<{ id: string; name: string }[]>([])
  const [loadingSubjects, setLoadingSubjects] = useState(true)
  const [grades, setGrades] = useState<{ id: string; name: string }[]>([])
  const [loadingGrades, setLoadingGrades] = useState(true)
  const [aiProviders, setAiProviders] = useState<AiProviderSummary[]>([])
  const [loadingAiProviders, setLoadingAiProviders] = useState(true)

  // zodResolver 与 useForm 在含 superRefine + coerce + default 时的输入/输出类型存在协变差异，
  // 使用 Resolver<ExamFormValues> 显式标注以替代 as any（从 zodResolver 返回类型收窄）
  const form = useForm<ExamFormValues>({
    resolver: zodResolver(formSchema) as Resolver<ExamFormValues>,
    defaultValues,
  })

  const preview = useExamPreview(form, t)

  useEffect(() => {
    const fetchMetadata = async () => {
      try {
        const [subjectsResult, gradesResult, aiProvidersResult] = await Promise.all([
          getSubjectsAction(),
          getGradesAction(),
          getAiProviderSummaries(),
        ])

        if (subjectsResult.success && subjectsResult.data) {
          setSubjects(subjectsResult.data)
          if (!form.getValues("subject") && subjectsResult.data.length > 0) {
            form.setValue("subject", subjectsResult.data[0].id)
          }
        } else {
          toast.error(t("exam.form.loadSubjectsFailed"))
        }

        if (gradesResult.success && gradesResult.data) {
          setGrades(gradesResult.data)
          if (!form.getValues("grade") && gradesResult.data.length > 0) {
            form.setValue("grade", gradesResult.data[0].id)
          }
        } else {
          toast.error(t("exam.form.loadGradesFailed"))
        }
        if (aiProvidersResult.success && aiProvidersResult.data) {
          setAiProviders(aiProvidersResult.data)
          const current = form.getValues("aiProviderId")
          if (!current) {
            const preferred = aiProvidersResult.data.find((item) => item.isDefault) ?? aiProvidersResult.data[0]
            if (preferred) {
              form.setValue("aiProviderId", preferred.id)
            }
          }
        }
      } catch (error) {
        console.error(error)
        toast.error(t("exam.form.loadFormFailed"))
      } finally {
        setLoadingSubjects(false)
        setLoadingGrades(false)
        setLoadingAiProviders(false)
      }
    }
    void fetchMetadata()
  }, [form, t])

  const mode = form.watch("mode")
  const isAiMode = mode === "ai"
  const isRichMode = mode === "rich"
  const previewSubject = form.watch("subject")
  const previewGrade = form.watch("grade")
  const previewDuration = form.watch("durationMin") ?? 90
  const previewTotalScore = form.watch("totalScore") ?? 100
  const previewTitleValue = form.watch("title")

  function onSubmit(data: ExamFormValues) {
    // 富文本模式不通过表单提交,直接跳转
    if (data.mode === "rich") {
      router.push("/teacher/exams/new")
      return
    }

    const resolvedTitle = data.mode === "ai" && !data.title?.trim() ? "AI Exam" : data.title?.trim() ?? ""
    const resolvedSubject = data.subject?.trim() || subjects[0]?.id || ""
    const resolvedGrade = data.grade?.trim() || grades[0]?.id || ""
    const resolvedDifficulty = Number.parseInt(String(data.difficulty ?? "3"), 10)
    const resolvedTotalScore = typeof data.totalScore === "number" && data.totalScore > 0 ? data.totalScore : 100
    const resolvedDurationMin = typeof data.durationMin === "number" && data.durationMin > 0 ? data.durationMin : 90

    if (data.mode === "ai" && (!resolvedSubject || !resolvedGrade)) {
      toast.error(t("exam.form.missingSubjectOrGrade"))
      return
    }
    if (data.mode === "ai") {
      const signature = preview.buildPreviewSignature(data)
      if (!preview.previewSignature || signature !== preview.previewSignature || preview.previewNodes.length === 0) {
        toast.error(t("exam.form.previewBeforeCreate"))
        return
      }
    }

    const formData = new FormData()
    formData.append("title", resolvedTitle)
    formData.append("subject", resolvedSubject)
    formData.append("grade", resolvedGrade)
    formData.append("difficulty", Number.isFinite(resolvedDifficulty) && resolvedDifficulty >= 1 && resolvedDifficulty <= 5 ? String(resolvedDifficulty) : "3")
    formData.append("totalScore", String(resolvedTotalScore))
    formData.append("durationMin", String(resolvedDurationMin))
    // P0-3: append exam mode + proctoring config fields
    formData.append("examMode", data.examMode ?? "homework")
    if (data.durationMinutes !== null && data.durationMinutes !== undefined) {
      formData.append("durationMinutes", String(data.durationMinutes))
    }
    formData.append("shuffleQuestions", String(data.shuffleQuestions ?? false))
    formData.append("allowLateStart", String(data.allowLateStart ?? false))
    formData.append("lateStartGraceMinutes", String(data.lateStartGraceMinutes ?? 0))
    formData.append("antiCheatEnabled", String(data.antiCheatEnabled ?? false))
    if (data.mode === "manual" && data.scheduledAt) {
      formData.append("scheduledAt", data.scheduledAt)
    }
    if (data.mode === "ai") {
      if (data.aiSourceText) formData.append("aiSourceText", data.aiSourceText)
      if (data.aiQuestionCount) formData.append("aiQuestionCount", data.aiQuestionCount.toString())
      if (data.aiProviderId) formData.append("aiProviderId", data.aiProviderId)
      const payload = preview.buildPreviewPayload(preview.previewNodes)
      if (payload.questions.length > 0) {
        formData.append("aiQuestionsJson", JSON.stringify(payload.questions))
        formData.append("structureJson", JSON.stringify(payload.structure))
      }
    }

    startTransition(async () => {
      const result = data.mode === "ai"
        ? await createAiExamAction(null, formData)
        : await createExamAction(null, formData)

      if (result.success && result.data) {
        toast.success(t("exam.form.createSuccess"), {
          description: t("exam.form.redirecting"),
        })
        router.push(`/teacher/exams/${result.data}/build`)
      } else {
        toast.error(result.message || t("exam.form.createFailed"))
      }
    })
  }

  const handleCreateClick = () => {
    if (isRichMode) {
      router.push("/teacher/exams/new")
      return
    }
    if (isAiMode) {
      preview.handleBackgroundPreview()
      return
    }
    form.handleSubmit(onSubmit)()
  }

  const handleConfirmCreate = () => {
    form.handleSubmit(onSubmit)()
  }

  const handleFormSubmit = (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    handleCreateClick()
  }

  const previewQuestionRows = preview.flattenPreviewQuestions(preview.previewNodes)
  const selectedPreviewQuestion = preview.selectedQuestionId
    ? preview.findPreviewQuestionNode(preview.previewNodes, preview.selectedQuestionId)
    : null
  const selectedPreviewContent = selectedPreviewQuestion?.question
    ? preview.parseEditableContent(selectedPreviewQuestion.question.content)
    : null
  const runningPreviewTaskCount = preview.previewTasks.filter((task) => task.status === "running").length
  const queuedPreviewTaskCount = preview.previewTasks.filter((task) => task.status === "queued").length
  const activePreviewTaskCount = runningPreviewTaskCount + queuedPreviewTaskCount
  const activePreviewMeta: PreviewSnapshotMeta = preview.previewMeta ?? {
    subject: previewSubject || "—",
    grade: previewGrade || "—",
    durationMin: previewDuration,
    totalScore: previewTotalScore,
  }

  return (
    <div className="space-y-6">
      {/* 顶部: 创建方式选择 */}
      <ExamModeSelector
        mode={mode}
        setMode={(value) => form.setValue("mode", value)}
        isPending={isPending}
        handleCreateClick={handleCreateClick}
      />

      {/* 富文本模式: 不显示下方表单 */}
      {isRichMode ? null : (
        <Form {...form}>
          <form onSubmit={handleFormSubmit} className="space-y-6">
            {/* 基本信息(始终可见) */}
            <ExamBasicInfoForm
              control={form.control}
              subjects={subjects}
              grades={grades}
              loadingSubjects={loadingSubjects}
              loadingGrades={loadingGrades}
            />

            {/* AI 模式: 显示 AI 生成器 */}
            {isAiMode && (
              <ExamAiGenerator
                form={form}
                control={form.control}
                aiProviders={aiProviders}
                setAiProviders={setAiProviders}
                loadingAiProviders={loadingAiProviders}
                handlePreview={preview.handlePreview}
                handleBackgroundPreview={preview.handleBackgroundPreview}
                previewLoading={preview.previewLoading}
                previewTasks={preview.previewTasks}
                handleOpenPreviewTask={preview.handleOpenPreviewTask}
                activePreviewTaskCount={activePreviewTaskCount}
                runningPreviewTaskCount={runningPreviewTaskCount}
                queuedPreviewTaskCount={queuedPreviewTaskCount}
              />
            )}

            {/* 考试模式配置(始终可见) */}
            <ExamModeConfig />
          </form>
        </Form>
      )}

      <ExamPreviewDialog
        previewOpen={preview.previewOpen}
        setPreviewOpen={preview.setPreviewOpen}
        previewLoading={preview.previewLoading}
        previewNodes={preview.previewNodes}
        previewTitle={preview.previewTitle}
        previewRawOutput={preview.previewRawOutput}
        previewMeta={preview.previewMeta}
        selectedQuestionId={preview.selectedQuestionId}
        setSelectedQuestionId={preview.setSelectedQuestionId}
        rewriteInstruction={preview.rewriteInstruction}
        setRewriteInstruction={preview.setRewriteInstruction}
        rewritingQuestion={preview.rewritingQuestion}
        previewQuestionRows={previewQuestionRows}
        selectedPreviewQuestion={selectedPreviewQuestion}
        selectedPreviewContent={selectedPreviewContent}
        activePreviewMeta={activePreviewMeta}
        updatePreviewQuestionNode={preview.updatePreviewQuestionNode}
        parseEditableContent={preview.parseEditableContent}
        handleRewriteSelectedQuestion={preview.handleRewriteSelectedQuestion}
        handleConfirmCreate={handleConfirmCreate}
        previewTitleValue={previewTitleValue}
      />
    </div>
  )
}
