import { useMutation, useQuery, useQueryClient, useInfiniteQuery } from '@tanstack/react-query'
import { imService, RtcOperation } from '@/services/im'
import { imKeys } from '@/lib/query-keys'
import { tokenManager } from '@/lib/auth/token'
import { userService } from '@/services/user'

export function useIMAccount() {
  return useMutation({
    mutationFn: () => imService.getIMAccount(),
  })
}

export function useGetIMAccount() {
  return useQuery({
    queryKey: imKeys.imAccount(),
    queryFn: () => imService.getIMAccount(),
    enabled: tokenManager.isAuthenticated(),
  })
}

export function useGetTextFromAsrVoice() {
  return useMutation({
    mutationFn: (data: { data: string; aiId: number }) => imService.getTextFromAsrVoice(data),
  })
}

export function useGetIMUserInfo({ aiId }: { aiId: number }) {
  return useQuery({
    queryKey: imKeys.imUserInfo(aiId),
    queryFn: () => imService.getIMUserInfo({ aiId }),
    enabled: !!aiId,
    gcTime: 1000 * 60 * 5, // 5分钟后清理缓存
    refetchOnMount: true, // 组件挂载时重新获取数据
    refetchOnWindowFocus: true, // 窗口聚焦时重新获取数据
  })
}

export function useGetShareUserInfo({ aiId }: { aiId: number }) {
  return useQuery({
    queryKey: imKeys.shareUserInfo(aiId),
    queryFn: () => imService.getShareUserInfo({ aiId }),
    enabled: !!aiId,
  })
}

export function useGetGiftList() {
  return useQuery({
    queryKey: imKeys.giftList(),
    queryFn: () => imService.getGiftList({ pn: 1, ps: 100 }),
    enabled: tokenManager.isAuthenticated(),
  })
}

export function useSendGift() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (data: { giftId: string; aiId: number; num: number }) => imService.sendGift(data),
    onSuccess: (_, data) => {
      const { aiId } = data
      queryClient.invalidateQueries({ queryKey: imKeys.heartbeatLevel(aiId) })
      queryClient.invalidateQueries({ queryKey: imKeys.imUserInfo(aiId) })
      queryClient.invalidateQueries({ queryKey: imKeys.giftList() })
    },
  })
}

export function useSetShowRelationship({ aiId }: { aiId: number }) {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (data: { aiId: number; isShow: boolean }) => imService.setShowRelationship(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [...imKeys.heartbeatRelationList(''), 'infinite'] })
    },
  })
}

export function useGetHeartbeatLevel({
  aiId,
  enabled = true,
}: {
  aiId: number
  enabled?: boolean
}) {
  return useQuery({
    queryKey: imKeys.heartbeatLevel(aiId),
    queryFn: () => imService.getHeartbeatLevel(aiId),
    enabled: !!aiId && enabled,
  })
}

export function useBuyHeartbeat({ aiId }: { aiId: number }) {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: { aiId: number; heartbeatVal: number }) => imService.buyHeartbeat(data),
  })
}

export function useGetMyChatSetting({ aiId }: { aiId: number }) {
  return useQuery({
    queryKey: imKeys.myChatSetting(aiId),
    queryFn: () => imService.getMyChatSetting(aiId),
    enabled: !!aiId,
  })
}

export function useSetMyChatSetting({ aiId }: { aiId: number }) {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: { aiId: number; nickname: string; birthday: number; whoAmI: string }) =>
      imService.setMyChatSetting(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: imKeys.myChatSetting(aiId) })
    },
  })
}

export function useGetChatBubbleDictList({ aiId }: { aiId: number }) {
  return useQuery({
    queryKey: imKeys.chatBubbleDictList(aiId),
    queryFn: () => imService.getChatBubbleDictList(aiId),
    enabled: !!aiId,
  })
}

export function useSetChatBubble({ aiId }: { aiId: number }) {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: { aiId: number; code: string }) => imService.setChatBubble(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: imKeys.imUserInfo(aiId) })
    },
  })
}

export function useGetRtcToken({ roomId }: { roomId: string }) {
  return useQuery({
    queryKey: imKeys.rtcToken(roomId),
    queryFn: () => imService.getRtcToken({ roomId }),
    enabled: !!roomId,
  })
}

export function useDoRtcOperation() {
  return useMutation({
    mutationFn: ({
      data,
      signal,
    }: {
      data: {
        roomId: string
        optType: RtcOperation
        aiId: number
        taskId: string
        duration?: number
      }
      signal?: AbortSignal
    }) => imService.doRtcOperation(data, signal),
  })
}

export function useStartVoiceChat() {
  return useMutation({
    mutationFn: (data: any) => {
      return fetch('/api/startVoice', {
        method: 'POST',
        body: JSON.stringify(data),
      }).then((res) => res.json())
    },
  })
}

export function useGetChatBackgroundList({ aiId }: { aiId: number }) {
  return useQuery({
    queryKey: imKeys.chatBackgroundList(aiId),
    queryFn: () => imService.getChatBackgroundList(aiId),
    enabled: !!aiId,
  })
}

export function useBatchAddBackground({ aiId }: { aiId: number }) {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: {
      aiId: number
      images: { url: string; width: number; height: number }[]
    }) => imService.batchAddBackground(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: imKeys.chatBackgroundList(aiId) })
    },
  })
}

export function useSetChatBackground({ aiId }: { aiId: number }) {
  return useMutation({
    mutationFn: (data: { aiId: number; backgroundId?: number | string }) =>
      imService.setChatBackground(data),
  })
}

export function useDelChatBackground({
  aiId,
  backgroundId,
}: {
  aiId: number
  backgroundId: number
}) {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: { aiId: number; backgroundId: number }) => imService.delChatBackground(data),
    onSuccess: () => {
      queryClient.setQueryData(imKeys.chatBackgroundList(aiId), (old: any) => {
        return old.filter((item: any) => item.backgroundId !== backgroundId)
      })
      queryClient.invalidateQueries({ queryKey: imKeys.imUserInfo(aiId) })
    },
  })
}

export function useDoFeedback() {
  return useMutation({
    mutationFn: (data: { aiId: number; messageId: string; content: string; optType: 1 | 2 | 0 }) =>
      imService.doFeedback(data),
  })
}

export function useGenSupContentV2() {
  return useMutation({
    mutationFn: (data: { aiId: number; batchNo?: string; excContentList?: string[] }) =>
      imService.genSupContentV2(data),
  })
}

export function useGetHeartbeatRelationList({ nickname }: { nickname: string }) {
  return useQuery({
    queryKey: imKeys.heartbeatRelationList(nickname),
    queryFn: () => imService.getHeartbeatRelationList({ nickname, page: { pn: 1, ps: 20 } }),
    enabled: !!nickname,
  })
}

export function useHeartbeatRelationListInfinite({ nickname = '' }: { nickname?: string } = {}) {
  return useInfiniteQuery({
    queryKey: [...imKeys.heartbeatRelationList(nickname), 'infinite'],
    queryFn: ({ pageParam = 1 }) =>
      imService.getHeartbeatRelationList({
        nickname,
        page: { pn: pageParam, ps: 20 },
      }),
    enabled: true, // 移除 nickname 的限制，允许获取所有联系人
    initialPageParam: 1,
    getNextPageParam: (lastPage, allPages) => {
      const currentPage = allPages.length
      const totalPages = Math.ceil((lastPage.tc || 0) / 20)
      return currentPage < totalPages ? currentPage + 1 : undefined
    },
    staleTime: 1000 * 60 * 5, // 5分钟缓存
  })
}

// 设备是否自动播放语音
export function useSetAutoPlayVoice() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (data: { aiId: number; isAutoPlayVoice: boolean }) =>
      userService.setAutoPlayVoice(data),
  })
}

export function useSendDialoguePrologueMessage() {
  return useMutation({
    mutationFn: (data: { aiId: number }) => imService.sendDialoguePrologueMessage(data),
  })
}

// 获取当前用户的心动值排名
export function useGetHeartbeatRank() {
  return useQuery({
    queryKey: imKeys.heartbeatRank(),
    queryFn: () => imService.getHeartbeatRank(),
    enabled: tokenManager.isAuthenticated(),
  })
}

export function useGetChatModelDictList() {
  return useQuery({
    queryKey: imKeys.chatModelDictList(),
    queryFn: () => imService.getChatModelDictList(),
  })
}

export function useDeleteConversations() {
  return useMutation({
    mutationFn: (data: { aiIdList: number[] }) => imService.deleteConversations(data),
  })
}

export function useGenAutoChatContent() {
  return useMutation({
    mutationFn: (data: { aiId: number }) => imService.genAutoChatContent(data),
  })
}
