import { useCallback } from 'react'
import { useNimMsgContext } from '@/context/NimChat/useNimChat'
import { ExtendedMessage, MessageLikeStatus } from '@/atoms/im'

/**
 * 消息点赞功能的自定义hook
 * 提供点赞、取消点赞、踩、取消踩的功能
 */
export const useMessageLike = () => {
  const { updateMessageLikeStatus } = useNimMsgContext()

  // 点赞消息
  const likeMessage = useCallback(
    async (message: ExtendedMessage) => {
      await updateMessageLikeStatus(message, MessageLikeStatus.Liked)
    },
    [updateMessageLikeStatus]
  )

  // 踩消息
  const dislikeMessage = useCallback(
    async (message: ExtendedMessage) => {
      await updateMessageLikeStatus(message, MessageLikeStatus.Disliked)
    },
    [updateMessageLikeStatus]
  )

  // 取消点赞/踩
  const cancelLikeMessage = useCallback(
    async (message: ExtendedMessage) => {
      await updateMessageLikeStatus(message, MessageLikeStatus.None)
    },
    [updateMessageLikeStatus]
  )

  // 切换点赞状态
  const toggleLike = useCallback(
    async (message: ExtendedMessage, currentStatus: MessageLikeStatus) => {
      const newStatus =
        currentStatus === MessageLikeStatus.Liked ? MessageLikeStatus.None : MessageLikeStatus.Liked
      await updateMessageLikeStatus(message, newStatus)
    },
    [updateMessageLikeStatus]
  )

  // 切换踩状态
  const toggleDislike = useCallback(
    async (message: ExtendedMessage, currentStatus: MessageLikeStatus) => {
      const newStatus =
        currentStatus === MessageLikeStatus.Disliked
          ? MessageLikeStatus.None
          : MessageLikeStatus.Disliked
      await updateMessageLikeStatus(message, newStatus)
    },
    [updateMessageLikeStatus]
  )

  return {
    likeMessage,
    dislikeMessage,
    cancelLikeMessage,
    toggleLike,
    toggleDislike,
  }
}
