import { useQuery, useMutation, useQueryClient, useInfiniteQuery } from '@tanstack/react-query'
import { userService } from '@/services/user'
import { aiUserKeys, authKeys, createKeys } from '@/lib/query-keys'
import {
  AiUserGiftsInput,
  AiUserInput,
  AiUserAlbumInput,
  LikedStatus,
  IAlbumItem,
  PageAlbumListOutput,
  LockStatus,
} from '@/services/user/types'

export function useGetAIUserBaseInfo(data: AiUserInput) {
  return useQuery({
    queryKey: aiUserKeys.baseInfo(data),
    queryFn: () => userService.getAIUserBaseInfo(data),
    enabled: !!data.aiId,
  })
}

export function useGetAIUserStat(data: AiUserInput) {
  return useQuery({
    queryKey: aiUserKeys.stat(data),
    queryFn: () => userService.getAIUserStat(data),
    enabled: !!data.aiId,
  })
}

export function useGetAIUserGifts(data: AiUserGiftsInput) {
  return useQuery({
    queryKey: aiUserKeys.gifts(data),
    queryFn: () => userService.getAIUserGifts(data),
    enabled: !!data.aiId,
  })
}

export function useGetAIUserAlbum(data: AiUserAlbumInput) {
  return useQuery({
    queryKey: aiUserKeys.album(data),
    queryFn: () => userService.getAIUserAlbum(data),
  })
}

// 新增无限滚动版本的相册查询
export function useGetAIUserAlbumInfinite(aiId: number, pageSize: number = 20) {
  return useInfiniteQuery({
    queryKey: ['aiUser', 'album', 'infinite', aiId],
    queryFn: async ({ pageParam = 1 }) => {
      const response = await userService.getAIUserAlbum({
        aiId,
        page: { pn: pageParam, ps: pageSize },
      })

      // 对每页的数据进行排序，将默认图片排在前面
      if (response.datas) {
        response.datas = response.datas.sort((a: IAlbumItem, b: IAlbumItem) => {
          if (a.isDefault && !b.isDefault) return -1
          if (!a.isDefault && b.isDefault) return 1
          return 0
        })
      }

      return response
    },
    getNextPageParam: (lastPage, allPages) => {
      const totalPages = Math.ceil((lastPage.tc || 0) / pageSize)
      const nextPage = allPages.length + 1
      return nextPage <= totalPages ? nextPage : undefined
    },
    initialPageParam: 1,
  })
}

// 点赞/取消点赞相册图片
export function useLikeAlbumImage() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (data: { albumId: number; likedStatus: LikedStatus; aiId: number }) =>
      userService.likeAlbumImage(data),
    onSuccess: (_, variables) => {
      const { albumId, likedStatus, aiId } = variables

      // 更新无限滚动版本的本地数据
      queryClient.setQueryData(['aiUser', 'album', 'infinite', aiId], (oldData: any) => {
        console.log(oldData)
        if (!oldData?.pages) return oldData

        return {
          ...oldData,
          pages: oldData.pages.map((page: PageAlbumListOutput) => ({
            ...page,
            datas: page.datas
              ?.map((item: IAlbumItem) => {
                console.log(item.albumId, albumId)
                if (item.albumId === albumId) {
                  // 更新点赞状态和点赞数
                  const currentLiked = item.likedStatus === LikedStatus.Liked
                  const newLiked = likedStatus === LikedStatus.Liked
                  const likedCountDiff = newLiked ? (currentLiked ? 0 : 1) : currentLiked ? -1 : 0

                  return {
                    ...item,
                    likedStatus: likedStatus,
                    likedCount: (item.likedCount || 0) + likedCountDiff,
                  }
                }
                return item
              })
              .sort((a: IAlbumItem, b: IAlbumItem) => {
                // 将默认图片排在第一位
                if (a.isDefault && !b.isDefault) return -1
                if (!a.isDefault && b.isDefault) return 1
                return 0
              }),
          })),
        }
      })
    },
  })
}

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

  return useMutation({
    mutationFn: (data: { aiId: number; imageId: number }) => userService.unlockAlbumImage(data),
    onSuccess: (_, variables) => {
      const { aiId, imageId } = variables

      // 更新无限滚动版本的本地数据
      queryClient.setQueryData(['aiUser', 'album', 'infinite', aiId], (oldData: any) => {
        if (!oldData?.pages) return oldData

        return {
          ...oldData,
          pages: oldData.pages.map((page: PageAlbumListOutput) => ({
            ...page,
            datas: page.datas
              ?.map((item: IAlbumItem) => {
                if (item.albumId === imageId) {
                  return {
                    ...item,
                    lockStatus: null, // 解锁后移除锁定状态
                  }
                }
                return item
              })
              .sort((a: IAlbumItem, b: IAlbumItem) => {
                // 将默认图片排在第一位
                if (a.isDefault && !b.isDefault) return -1
                if (!a.isDefault && b.isDefault) return 1
                return 0
              }),
          })),
        }
      })
    },
  })
}

// 设置默认相册图片
export function useSetDefaultAlbumImage() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (data: { aiId: number; albumId: number }) => userService.setDefaultAlbumImage(data),
    onSuccess: (_, variables) => {
      const { aiId, albumId } = variables

      queryClient.invalidateQueries({
        queryKey: aiUserKeys.baseInfo({ aiId }),
      })

      // 更新无限滚动版本的本地数据
      queryClient.setQueryData(['aiUser', 'album', 'infinite', aiId], (oldData: any) => {
        if (!oldData?.pages) return oldData

        return {
          ...oldData,
          pages: oldData.pages.map((page: PageAlbumListOutput) => ({
            ...page,
            datas: page.datas
              ?.map((item: IAlbumItem) => {
                if (item.albumId === albumId) {
                  return {
                    ...item,
                    isDefault: true,
                  }
                }
                return {
                  ...item,
                  isDefault: false,
                }
              })
              .sort((a: IAlbumItem, b: IAlbumItem) => {
                // 将默认图片排在第一位
                if (a.isDefault && !b.isDefault) return -1
                if (!a.isDefault && b.isDefault) return 1
                return 0
              }),
          })),
        }
      })
    },
  })
}

// 设置相册图片解锁方式
export function useSetAlbumImageUnlockMethod() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (data: { aiId: number; albumId: number; unlockPrice: number }) =>
      userService.setAlbumImageUnlockMethod(data),
    onSuccess: (_, variables) => {
      const { aiId, albumId, unlockPrice } = variables
      queryClient.setQueryData(['aiUser', 'album', 'infinite', aiId], (oldData: any) => {
        if (!oldData?.pages) return oldData

        return {
          ...oldData,
          pages: oldData.pages.map((page: PageAlbumListOutput) => ({
            ...page,
            datas: page.datas
              ?.map((item: IAlbumItem) => {
                if (item.albumId === albumId) {
                  return {
                    ...item,
                    unlockPrice: unlockPrice,
                    lockStatus: !!unlockPrice ? LockStatus.Lock : null,
                  }
                }
                return item
              })
              .sort((a: IAlbumItem, b: IAlbumItem) => {
                // 将默认图片排在第一位
                if (a.isDefault && !b.isDefault) return -1
                if (!a.isDefault && b.isDefault) return 1
                return 0
              }),
          })),
        }
      })
    },
  })
}

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

  return useMutation({
    mutationFn: (data: { aiId: number; albumId: number }) => userService.deleteAlbumImage(data),
    onSuccess: (_, variables) => {
      const { aiId, albumId } = variables
      queryClient.setQueryData(['aiUser', 'album', 'infinite', aiId], (oldData: any) => {
        if (!oldData?.pages) return oldData

        return {
          ...oldData,
          pages: oldData.pages.map((page: PageAlbumListOutput) => ({
            ...page,
            datas: page.datas?.filter((item: IAlbumItem) => item.albumId !== albumId),
          })),
        }
      })
    },
  })
}

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

  return useMutation({
    mutationFn: (data: { aiId: number }) => userService.deleteCharacter(data),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: createKeys.getAICharacterList(),
      })
      queryClient.invalidateQueries({
        queryKey: authKeys.currentUser(),
      })
    },
  })
}

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

  return useMutation({
    mutationFn: (data: {
      aiId: number
      images: Array<{ url: string; width: number; height: number; unlockPrice: number }>
    }) => userService.addAlbumImage(data),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ['aiUser', 'album', 'infinite', aiId],
      })
    },
  })
}

export function useUnlockImage() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: { aiId: number; albumId: number; messageServerId?: string }) =>
      userService.unlockImage(data),
    onSuccess: (resp, variables) => {
      const { aiId, albumId } = variables

      // 更新无限滚动版本的本地数据
      queryClient.setQueryData(['aiUser', 'album', 'infinite', aiId], (oldData: any) => {
        if (!oldData?.pages) return oldData

        return {
          ...oldData,
          pages: oldData.pages.map((page: PageAlbumListOutput) => ({
            ...page,
            datas: page.datas
              ?.map((item: IAlbumItem) => {
                if (item.albumId === albumId) {
                  return {
                    ...item,
                    lockStatus: LockStatus.Unlock,
                    ...resp,
                  }
                }
                return item
              })
              .sort((a: IAlbumItem, b: IAlbumItem) => {
                // 将默认图片排在第一位
                if (a.isDefault && !b.isDefault) return -1
                if (!a.isDefault && b.isDefault) return 1
                return 0
              }),
          })),
        }
      })
    },
  })
}

export function useViewUnlockAlbumImage() {
  return useMutation({
    mutationFn: (data: { aiId: number; albumId: number; messageServerId?: string }) =>
      userService.viewUnlockAlbumImage(data),
  })
}
