"use client"

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

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

type DialogState = ReturnType<typeof useKpDialogState>

interface UseKpDeleteArgs {
  textbookId: string | undefined
  highlightedKpId: string | null
  setHighlightedKpId: (id: string | null) => void
  dialog: DialogState
}

/**
 * 知识点删除 Hook。
 * 从 use-kp-crud 拆分，负责删除知识点的请求确认与异步执行。
 */
export function useKpDelete({
  textbookId,
  highlightedKpId,
  setHighlightedKpId,
  dialog,
}: UseKpDeleteArgs) {
  const t = useTranslations("textbooks")

  const requestDeleteKnowledgePoint = (kpId: string, e: React.MouseEvent): void => {
    e.stopPropagation()
    dialog.setPendingDeleteKpId(kpId)
    dialog.setDeleteConfirmOpen(true)
  }

  const confirmDeleteKnowledgePoint = async (): Promise<void> => {
    if (!dialog.pendingDeleteKpId || !textbookId) return
    dialog.setDeleteConfirmOpen(false)

    try {
      const result = await deleteKnowledgePointAction(dialog.pendingDeleteKpId, textbookId)
      if (result.success) {
        toast.success(result.message)
        if (highlightedKpId === dialog.pendingDeleteKpId) {
          setHighlightedKpId(null)
        }
      } else {
        toast.error(result.message)
      }
    } catch {
      toast.error(t("action.deleteFailed"))
    } finally {
      dialog.setPendingDeleteKpId(null)
    }
  }

  return { requestDeleteKnowledgePoint, confirmDeleteKnowledgePoint }
}
