"use client"

import { useTranslations } from "next-intl"
import { toast } from "sonner"

import { createKnowledgePointAction } from "../actions"

interface UseKpCreateArgs {
  selectedChapterId: string | null
  selectedChapterTextbookId: string | undefined
  onKpCreated?: () => void
}

/**
 * 知识点创建 Hook。
 * 从 use-kp-crud 拆分，负责创建知识点的异步操作与 toast 反馈。
 */
export function useKpCreate({
  selectedChapterId,
  selectedChapterTextbookId,
  onKpCreated,
}: UseKpCreateArgs) {
  const t = useTranslations("textbooks")

  const handleCreateKnowledgePoint = async (formData: FormData): Promise<boolean> => {
    if (!selectedChapterId || !selectedChapterTextbookId) return false

    try {
      const result = await createKnowledgePointAction(
        selectedChapterId,
        selectedChapterTextbookId,
        null,
        formData,
      )

      if (result.success) {
        toast.success(t("action.kpCreateSuccess"))
        onKpCreated?.()
        window.getSelection()?.removeAllRanges()
        return true
      }
      toast.error(result.message || t("action.kpCreateFailed"))
      return false
    } catch {
      toast.error(t("action.errorOccurred"))
      return false
    }
  }

  return { handleCreateKnowledgePoint }
}
