"use client"

import { useEffect, useRef, useState, useTransition, type FormEvent } from "react"
import { useRouter } from "next/navigation"
import { useTranslations } from "next-intl"
import { toast } from "sonner"
import { Sparkles, Save, FileText } from "lucide-react"

import { Button } from "@/shared/components/ui/button"
import { Input } from "@/shared/components/ui/input"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/components/ui/select"
import { ResizablePanel } from "@/shared/components/ui/resizable-panel"
import { ScrollArea } from "@/shared/components/ui/scroll-area"
import { getGradesAction, getSubjectsAction } from "../actions"
import { autoMarkExamAction } from "../ai-pipeline/auto-mark"
import {
  createExamFromRichEditorAction,
  updateExamFromRichEditorAction,
} from "../actions-rich-editor"
import {
  ExamRichEditor,
  type ExamRichEditorHandle,
  type EditorJSONContent,
  editorDocToStructure,
  type EditorDoc,
} from "../editor"
import { ExamPreview } from "./exam-preview"

interface ExamRichFormValues {
  title: string
  subject: string
  grade: string
  difficulty: string
  totalScore: number
  durationMin: number
  scheduledAt: string
}

interface ExamRichFormProps {
  /** 模式:create=新建(默认), edit=编辑已有 */
  mode?: "create" | "edit"
  /** 编辑模式下的试卷 ID */
  examId?: string
  /** 编辑模式下的初始标题 */
  initialTitle?: string
  /** 编辑模式下的初始编辑器内容 */
  initialContent?: EditorJSONContent | null
}

export function ExamRichForm({
  mode = "create",
  examId,
  initialTitle,
  initialContent,
}: ExamRichFormProps) {
  const router = useRouter()
  const t = useTranslations("examHomework")
  const difficultyOptions = [
    { value: "1", label: t("exam.form.difficultyLevel1") },
    { value: "2", label: t("exam.form.difficultyLevel2") },
    { value: "3", label: t("exam.form.difficultyLevel3") },
    { value: "4", label: t("exam.form.difficultyLevel4") },
    { value: "5", label: t("exam.form.difficultyLevel5") },
  ]
  const editorRef = useRef<ExamRichEditorHandle>(null)
  const [isPending, startTransition] = useTransition()
  const [isMarking, startMarking] = useTransition()
  const isEditMode = mode === "edit"

  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 [values, setValues] = useState<ExamRichFormValues>({
    title: initialTitle ?? "",
    subject: "",
    grade: "",
    difficulty: "3",
    totalScore: 100,
    durationMin: 90,
    scheduledAt: "",
  })

  const [editorDoc, setEditorDoc] = useState<EditorJSONContent | null>(initialContent ?? null)

  // 编辑模式下不需要加载 subjects/grades
  useEffect(() => {
    if (isEditMode) {
      setLoadingSubjects(false)
      setLoadingGrades(false)
      return
    }
    const fetchMetadata = async () => {
      try {
        const [subjectsResult, gradesResult] = await Promise.all([
          getSubjectsAction(),
          getGradesAction(),
        ])
        if (subjectsResult.success && subjectsResult.data) {
          const data = subjectsResult.data
          setSubjects(data)
          if (data.length > 0) {
            setValues((v) => ({ ...v, subject: data[0].id }))
          }
        }
        if (gradesResult.success && gradesResult.data) {
          const data = gradesResult.data
          setGrades(data)
          if (data.length > 0) {
            setValues((v) => ({ ...v, grade: data[0].id }))
          }
        }
      } catch (e) {
        console.error("[ExamRichForm]", e)
        toast.error(t("exam.richEditor.loadFormFailed"))
      } finally {
        setLoadingSubjects(false)
        setLoadingGrades(false)
      }
    }
    void fetchMetadata()
  }, [t, isEditMode])

  /**
   * AI 自动标记 —— 从编辑器当前内容获取文本,交给 AI 解析后重新载入。
   * 用户可直接在编辑器中粘贴试卷文本,然后点击此按钮让 AI 自动标记题目结构。
   */
  const handleAutoMark = () => {
    const currentText = editorRef.current?.getText() ?? ""
    if (!currentText.trim()) {
      toast.error(t("exam.richEditor.emptyEditor"))
      return
    }
    startMarking(async () => {
      const formData = new FormData()
      formData.append("sourceText", currentText)
      const result = await autoMarkExamAction(null, formData)
      if (result.success && result.data) {
        const doc = result.data.doc as EditorJSONContent
        editorRef.current?.setJSON(doc)
        setEditorDoc(doc)
        if (result.data.title) {
          setValues((v) => ({ ...v, title: result.data!.title }))
        }
        toast.success(result.message || t("exam.richEditor.aiMarkSuccess"))
      } else {
        toast.error(result.message || t("exam.richEditor.aiMarkFailed"))
      }
    })
  }

  const handleSubmit = (e: FormEvent) => {
    e.preventDefault()
    const doc = editorRef.current?.getJSON()
    if (!doc) {
      toast.error(t("exam.richEditor.emptyContent"))
      return
    }
    if (!values.title.trim()) {
      toast.error(t("exam.richEditor.titleRequired"))
      return
    }

    if (isEditMode) {
      if (!examId) {
        toast.error(t("exam.richForm.missingExamId"))
        return
      }
      startTransition(async () => {
        const formData = new FormData()
        formData.append("examId", examId)
        formData.append("title", values.title)
        formData.append("editorDoc", JSON.stringify(doc))

        const result = await updateExamFromRichEditorAction(null, formData)
        if (result.success) {
          toast.success(result.message || t("exam.richEditor.saveSuccess"))
          router.push(`/teacher/exams/${examId}/build`)
        } else {
          toast.error(result.message || t("exam.richEditor.saveFailed"))
        }
      })
      return
    }

    if (!values.subject || !values.grade) {
      toast.error(t("exam.richEditor.subjectGradeRequired"))
      return
    }

    startTransition(async () => {
      const formData = new FormData()
      formData.append("title", values.title)
      formData.append("subject", values.subject)
      formData.append("grade", values.grade)
      formData.append("difficulty", values.difficulty)
      formData.append("totalScore", String(values.totalScore))
      formData.append("durationMin", String(values.durationMin))
      formData.append("scheduledAt", values.scheduledAt)
      formData.append("editorDoc", JSON.stringify(doc))
      formData.append("examMode", "homework")

      const result = await createExamFromRichEditorAction(null, formData)
      if (result.success && result.data) {
        toast.success(result.message || t("exam.richEditor.saveSuccess"))
        router.push(`/teacher/exams/${result.data}/build`)
      } else {
        toast.error(result.message || t("exam.richEditor.saveFailed"))
      }
    })
  }

  const handleEditorChange = (doc: EditorJSONContent) => {
    setEditorDoc(doc)
  }

  const previewStructure = editorDoc
    ? editorDocToStructure(editorDoc, values.title)
    : null

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      {/* 顶部工具栏:基本信息(单行) + AI 自动标记 + 保存 */}
      <div className="flex flex-wrap items-center gap-3 rounded-md border bg-card p-3">
        <Input
          placeholder={t("exam.richEditor.titlePlaceholder")}
          value={values.title}
          onChange={(e) => setValues((v) => ({ ...v, title: e.target.value }))}
          className="h-9 min-w-[200px] flex-1"
        />
        {!isEditMode && (
          <>
            <Select
              value={values.subject}
              onValueChange={(val) => setValues((v) => ({ ...v, subject: val }))}
              disabled={loadingSubjects}
            >
              <SelectTrigger className="h-9 w-[120px]">
                <SelectValue placeholder={loadingSubjects ? "..." : t("exam.form.subject")} />
              </SelectTrigger>
              <SelectContent>
                {subjects.map((s) => (
                  <SelectItem key={s.id} value={s.id}>
                    {s.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Select
              value={values.grade}
              onValueChange={(val) => setValues((v) => ({ ...v, grade: val }))}
              disabled={loadingGrades}
            >
              <SelectTrigger className="h-9 w-[120px]">
                <SelectValue placeholder={loadingGrades ? "..." : t("exam.form.grade")} />
              </SelectTrigger>
              <SelectContent>
                {grades.map((g) => (
                  <SelectItem key={g.id} value={g.id}>
                    {g.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Select
              value={values.difficulty}
              onValueChange={(val) => setValues((v) => ({ ...v, difficulty: val }))}
            >
              <SelectTrigger className="h-9 w-[100px]">
                <SelectValue placeholder={t("exam.form.difficulty")} />
              </SelectTrigger>
              <SelectContent>
                {difficultyOptions.map((o) => (
                  <SelectItem key={o.value} value={o.value}>
                    {o.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Input
              type="number"
              min={1}
              value={String(values.totalScore)}
              onChange={(e) => setValues((v) => ({ ...v, totalScore: Number(e.target.value) || 0 }))}
              className="h-9 w-[90px]"
              title={t("exam.form.totalScore")}
            />
            <Input
              type="number"
              min={10}
              value={String(values.durationMin)}
              onChange={(e) => setValues((v) => ({ ...v, durationMin: Number(e.target.value) || 0 }))}
              className="h-9 w-[90px]"
              title={t("exam.form.durationMin")}
            />
          </>
        )}

        <div className="ml-auto flex items-center gap-2">
          {isEditMode && (
            <Button
              type="button"
              variant="ghost"
              size="sm"
              onClick={() => router.push(`/teacher/exams/${examId}/build`)}
              className="gap-2 text-muted-foreground hover:text-foreground"
            >
              <FileText className="h-4 w-4" />
              {t("exam.richForm.backToBuild")}
            </Button>
          )}
          <Button
            type="button"
            variant="outline"
            size="sm"
            onClick={handleAutoMark}
            disabled={isMarking}
            className="gap-2"
            title={t("exam.richEditor.aiMarkHint")}
          >
            <Sparkles className="h-4 w-4" />
            {isMarking ? t("exam.richEditor.aiMarking") : t("exam.richEditor.aiAutoMark")}
          </Button>
          <Button type="submit" disabled={isPending} size="sm" className="gap-2">
            <Save className="h-4 w-4" />
            {isPending ? t("exam.richEditor.saving") : t("exam.richEditor.saveDraft")}
          </Button>
        </div>
      </div>

      {/* 编辑器 + 预览(可拖拽分栏) */}
      <div className="h-[calc(100vh-180px)] rounded-md border">
        <ResizablePanel
          initialLeft={60}
          minLeft={30}
          minRight={25}
          left={
            <div className="flex h-full flex-col">
              <div className="border-b bg-muted/30 px-3 py-2 text-xs font-medium text-muted-foreground">
                {t("exam.richEditor.editorArea")}
              </div>
              <div className="flex-1 min-h-0">
                <ExamRichEditor
                  ref={editorRef}
                  initialContent={initialContent}
                  onChange={handleEditorChange}
                  className="h-full rounded-none border-0 shadow-none"
                />
              </div>
            </div>
          }
          right={
            <div className="flex h-full flex-col">
              <div className="border-b bg-muted/30 px-3 py-2 text-xs font-medium text-muted-foreground">
                {t("exam.richEditor.previewArea")}
              </div>
              <ScrollArea className="flex-1">
                <div className="p-4">
                  {previewStructure && previewStructure.questions.length > 0 ? (
                    <ExamPreview structure={previewStructure} />
                  ) : (
                    <div className="flex h-full items-center justify-center py-20 text-center text-sm text-muted-foreground">
                      <div>
                        <FileText className="mx-auto mb-2 h-8 w-8 opacity-50" />
                        {t("exam.richEditor.emptyPreview")}
                      </div>
                    </div>
                  )}
                </div>
              </ScrollArea>
            </div>
          }
        />
      </div>
    </form>
  )
}
