"use client"

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

import type { KnowledgePoint } from "../types"
import {
  createKnowledgePointAction,
  deleteKnowledgePointAction,
  updateKnowledgePointAction,
} from "../actions"
import type { useKpDialogState } from "./use-kp-dialog-state"

type DialogState = ReturnType<typeof useKpDialogState>

interface UseKpCrudArgs {
  textbookId: string | undefined
  selectedChapterId: string | null
  selectedChapterTextbookId: string | undefined
  highlightedKpId: string | null
  setHighlightedKpId: (id: string | null) => void
  onKpCreated?: () => void
  dialog: DialogState
}

/**
 * 知识点 CRUD 操作 Hook。
 *
 * 依赖 useKpDialogState 提供的对话框状态，执行创建/更新/删除操作。
 */
export function useKpCrud({
  textbookId,
  selectedChapterId,
  selectedChapterTextbookId,
  highlightedKpId,
  setHighlightedKpId,
  onKpCreated,
  dialog,
}: UseKpCrudArgs) {
  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
    }
  }

  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)
    }
  }

  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 {
    handleCreateKnowledgePoint,
    requestDeleteKnowledgePoint,
    confirmDeleteKnowledgePoint,
    handleUpdateKnowledgePoint,
  }
}

export type { KnowledgePoint }
