"use client"

import { useTransition } from "react"
import type { JSX } from "react"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { useTranslations } from "next-intl"

import { ErrorBookList } from "@/modules/error-book/components/error-book-list"
import { AiErrorBookAnalysis } from "@/modules/ai/components/ai-error-book-analysis"
import { createPracticeSessionAction } from "@/modules/adaptive-practice/actions"
import type { ErrorBookItem } from "@/modules/error-book/types"

/**
 * 从题目内容中提取纯文本（用于 AI 分析）
 */
function extractQuestionText(content: unknown): string {
  if (!content) return ""
  if (typeof content === "string") return content
  if (typeof content === "object" && content !== null && "text" in content) {
    const textValue = (content as Record<string, unknown>).text
    if (typeof textValue === "string") return textValue
  }
  try {
    return JSON.stringify(content)
  } catch {
    return ""
  }
}

/**
 * 将错题条目转换为 AI 薄弱点分析所需的输入格式
 */
function mapErrorItemsForAnalysis(items: ErrorBookItem[]): Array<{
  questionText: string
  questionType: string
  knowledgePointIds?: string[]
  errorCount: number
  masteryLevel: number
}> {
  return items.map((it) => ({
    questionText: extractQuestionText(it.question?.content),
    questionType: it.question?.type ?? "unknown",
    knowledgePointIds: it.knowledgePointIds ?? undefined,
    errorCount: it.reviewCount > 0 ? it.reviewCount : 1,
    masteryLevel: it.masteryLevel,
  }))
}

interface StudentErrorBookListClientProps {
  items: ErrorBookItem[]
  studentId: string
}

/**
 * 学生端错题本列表客户端包装组件（位于 app 层）。
 *
 * 负责将 AI 分析和变式练习功能通过 props 注入到 ErrorBookList，
 * 避免 error-book 模块直接 import ai / adaptive-practice 模块（解耦）。
 * app 层可以 import 任何模块，因此跨模块依赖在此合法。
 */
export function StudentErrorBookListClient({
  items,
  studentId,
}: StudentErrorBookListClientProps): JSX.Element {
  const router = useRouter()
  const t = useTranslations("errorBook")
  const tPractice = useTranslations("practice")
  const [, startTransition] = useTransition()

  const aiAnalysisSlot = (item: ErrorBookItem): React.ReactNode => {
    const currentQuestionText = extractQuestionText(item.question?.content)
    if (!currentQuestionText) return null

    const aiErrorItems = mapErrorItemsForAnalysis(items)

    return (
      <AiErrorBookAnalysis
        studentId={studentId}
        subjectId={item.subjectId ?? undefined}
        currentQuestionText={currentQuestionText}
        currentQuestionType={item.question?.type}
        errorItems={aiErrorItems}
      />
    )
  }

  const onStartVariantPractice = (item: ErrorBookItem): void => {
    startTransition(async () => {
      const formData = new FormData()
      formData.append(
        "json",
        JSON.stringify({
          practiceType: "error_variant",
          subjectId: item.subjectId ?? undefined,
          sourceMeta: {
            errorBookItemIds: [item.id],
            sourceQuestionIds: [item.questionId],
          },
          questionCount: 10,
        }),
      )
      const res = await createPracticeSessionAction(undefined, formData)
      if (res.success && res.data) {
        toast.success(res.message ?? tPractice("starter.title"))
        router.push(`/student/practice/${res.data.sessionId}`)
      } else {
        toast.error(res.message ?? t("messages.saveFailed"))
      }
    })
  }

  return (
    <ErrorBookList
      items={items}
      aiAnalysisSlot={aiAnalysisSlot}
      onStartVariantPractice={onStartVariantPractice}
    />
  )
}
