"use client"

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

import { updateKnowledgePointAction } from "../actions"
import type { useKpDialogState } from "./use-kp-dialog-state"

type DialogState = ReturnType<typeof useKpDialogState>

interface UseKpUpdateArgs {
  textbookId: string | undefined
  dialog: DialogState
}

/**
 * 知识点更新 Hook。
 * 从 use-kp-crud 拆分，负责更新知识点信息的异步操作与 toast 反馈。
 */
export function useKpUpdate({ textbookId, dialog }: UseKpUpdateArgs) {
  const t = useTranslations("textbooks")

  const handleUpdateKnowledgePoint = async (formData: FormData): Promise<void> => {
    if (!dialog.editingKp || !textbookId) return
    dialog.setIsUpdatingKp(true)

    try {
      const result = await updateKnowledgePointAction(dialog.editingKp.id, textbookId, null, formData)
      if (result.success) {
        toast.success(result.message)
        dialog.setEditKpDialogOpen(false)
        dialog.setEditingKp(null)
      } else {
        toast.error(result.message)
      }
    } catch {
      toast.error(t("action.updateFailedGeneric"))
    } finally {
      dialog.setIsUpdatingKp(false)
    }
  }

  return { handleUpdateKnowledgePoint }
}
