import { useMutation, useQuery, useQueryClient, useInfiniteQuery } from '@tanstack/react-query'
import {
  GetSubProductCheckoutLinkRequest,
  GetWalletBalanceResponse,
  GetWebChargeCheckoutRequest,
  GetWebChargeCheckoutResultRequest,
  GetWebChargePreOrderRequest,
  WalletBalanceInYuan,
  walletService,
  getTransactionListRequest,
  TransactionType,
} from '@/services/wallet'
import { walletKeys } from '@/lib/query-keys'
import { tokenManager } from '@/lib/auth/token'
import { formatFromCents } from '@/utils/number'
import numeral from 'numeral'
import { useCurrentUser } from './auth'

export enum ChatPriceType {
  TEXT,
  VOICE,
  VOICE_CALL,
  BACKGROUND_IMAGE,
}

export const ChatPriceTypeMap = {
  [ChatPriceType.TEXT]: 1,
  [ChatPriceType.VOICE]: 10,
  [ChatPriceType.VOICE_CALL]: 20,
  [ChatPriceType.BACKGROUND_IMAGE]: 70,
}

export const COIN_INSUFFICIENT_ERROR_CODE = 'INSUFFICIENT_BALANCE'

// 货币转换工具函数
const convertCentsToYuan = (cents?: number): number | undefined => {
  return cents ? cents / 100 : undefined
}

export function useGetWalletBalance() {
  return useQuery({
    queryKey: walletKeys.getWalletBalance(),
    queryFn: async () => {
      const response = await walletService.getWalletBalance()
      // 将接口返回的分转换为元（除以100）
      return {
        ...response,
        awaitingIncome: convertCentsToYuan(response.awaitingIncome),
        balance: formatFromCents(response.balance, 0, false),
        // balance: 0,
        balanceString: formatFromCents(response.balance),
        // balanceString: '0',
        income: convertCentsToYuan(response.income),
        requestWithdraw: convertCentsToYuan(response.requestWithdraw),
        withdrawable: convertCentsToYuan(response.withdrawable),
        // wdFeeRate 是比例，不需要转换
      }
    },
    enabled: tokenManager.isAuthenticated(),
    staleTime: 1000 * 60 * 1,
  })
}

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

  // 注意：这里处理的金额单位是元（已经从接口返回的分转换过）
  // 乐观更新的核心方法，支持回滚
  const optimisticUpdate = (
    updater: (currentBalance: number) => number,
    options?: { skipInvalidation?: boolean }
  ) => {
    const queryKey = walletKeys.getWalletBalance()

    // 保存当前数据用于回滚
    const previousData = queryClient.getQueryData<WalletBalanceInYuan>(queryKey)

    // 乐观更新
    queryClient.setQueryData(queryKey, (oldData: WalletBalanceInYuan | undefined) => {
      if (!oldData) return oldData

      const currentBalance = oldData.balance || 0
      const newBalance = updater(currentBalance)

      return {
        ...oldData,
        balance: Math.max(0, newBalance), // 确保余额不会为负数
        balanceString: numeral(Math.max(0, newBalance)).format('0,0'),
      }
    })

    // 返回回滚函数
    const rollback = () => {
      queryClient.setQueryData(queryKey, previousData)
    }

    // 如果不跳过验证，则重新获取数据
    if (!options?.skipInvalidation) {
      queryClient.invalidateQueries({ queryKey })
    }

    return { rollback, previousData }
  }

  return {
    // 减少余额（送礼物时使用）- 支持回滚
    // 参数 amount 单位为元，例如：deduct(1.5) 表示扣除 1.5 元
    deduct: (amount: number, options?: { skipInvalidation?: boolean }) => {
      if (amount <= 0) {
        console.warn('扣除金额必须大于0')
        return { rollback: () => {}, previousData: undefined }
      }

      const currentData = queryClient.getQueryData<WalletBalanceInYuan>(
        walletKeys.getWalletBalance()
      )
      const currentBalance = currentData?.balance || 0

      // 检查余额是否足够
      if (currentBalance < amount) {
        console.warn('余额不足，无法扣除')
        return { rollback: () => {}, previousData: undefined }
      }

      return optimisticUpdate((current) => current - amount, options)
    },

    // 增加余额（充值时使用）
    // 参数 amount 单位为元，例如：add(10) 表示增加 10 元
    add: (amount: number, options?: { skipInvalidation?: boolean }) => {
      if (amount <= 0) {
        console.warn('增加金额必须大于0')
        return { rollback: () => {}, previousData: undefined }
      }
      return optimisticUpdate((current) => current + amount, options)
    },

    // 直接设置余额
    // 参数 newBalance 单位为元，例如：set(50) 表示设置余额为 50 元
    set: (newBalance: number, options?: { skipInvalidation?: boolean }) => {
      if (newBalance < 0) {
        console.warn('余额不能为负数')
        return { rollback: () => {}, previousData: undefined }
      }
      return optimisticUpdate(() => newBalance, options)
    },

    // 检查余额是否足够
    // 参数 amount 单位为元，例如：checkSufficient(1.5) 检查是否有 1.5 元
    checkSufficient: (amount: number): boolean => {
      const currentData = queryClient.getQueryData<WalletBalanceInYuan>(
        walletKeys.getWalletBalance()
      )
      const currentBalance = currentData?.balance || 0
      return currentBalance >= amount
    },

    checkSufficientByType: (type: ChatPriceType): boolean => {
      const amount = ChatPriceTypeMap[type]
      const currentData = queryClient.getQueryData<WalletBalanceInYuan>(
        walletKeys.getWalletBalance()
      )
      const currentBalance = currentData?.balance || 0
      return currentBalance >= amount
    },

    // 获取当前余额（单位：元）
    getCurrentBalance: (): number => {
      const currentData = queryClient.getQueryData<WalletBalanceInYuan>(
        walletKeys.getWalletBalance()
      )
      return currentData?.balance || 0
    },

    // 重新获取最新余额（从服务器）
    refresh: () => {
      queryClient.invalidateQueries({ queryKey: walletKeys.getWalletBalance() })
    },
  }
}

export function useGetChargeProductList() {
  const { data: user } = useCurrentUser()
  return useQuery({
    queryKey: walletKeys.getChargeProductList(),
    queryFn: async () => {
      const response = await walletService.getChargeProductList()
      return response
    },
    enabled: tokenManager.isAuthenticated() && !!user,
  })
}

export function useGetWebChargePreOrder() {
  return useMutation({
    mutationFn: async (data: GetWebChargePreOrderRequest) => {
      const response = await walletService.getWebChargePreOrder(data)
      return response
    },
  })
}

export function useGetWebChargeCheckout() {
  return useMutation({
    mutationFn: async (data: GetWebChargeCheckoutRequest) => {
      const response = await walletService.getWebChargeCheckout(data)
      return response
    },
  })
}

export function useGetWebChargeCheckoutResult() {
  return useMutation({
    mutationFn: async (data: GetWebChargeCheckoutResultRequest) => {
      const response = await walletService.getCheckoutResult(data)
      return response
    },
  })
}

export function useGetMemberDetail(options?: { enabled?: boolean }) {
  return useQuery({
    queryKey: walletKeys.getMemberDetail(),
    queryFn: async () => {
      const response = await walletService.getMemberDetail()
      return response
    },
    enabled: options?.enabled,
  })
}

export function useGetSubProductList() {
  const { data: user } = useCurrentUser()
  return useQuery({
    queryKey: walletKeys.getSubProductList(),
    queryFn: async () => {
      const response = await walletService.getSubProductList()
      return response
    },
    enabled: tokenManager.isAuthenticated() && !!user,
  })
}

export function useGetSubProductCheckoutLink() {
  return useMutation({
    mutationFn: async (data: GetSubProductCheckoutLinkRequest) => {
      const response = await walletService.getSubProductCheckoutLink(data)
      return response
    },
  })
}

// 交易记录列表参数接口
export interface UseGetTransactionListParams {
  type?: TransactionType
  startTime?: number
  endTime?: number
  pageSize?: number
}

/**
 * 获取交易记录列表的无限滚动 hook
 * 支持上拉加载更多数据
 */
export function useGetTransactionList(params: UseGetTransactionListParams = {}) {
  const { type, startTime, endTime, pageSize = 20 } = params

  return useInfiniteQuery({
    queryKey: walletKeys.getTransactionList({ type, startTime, endTime }),
    queryFn: async ({ pageParam = 1 }) => {
      const requestParams: getTransactionListRequest = {
        type,
        startTime,
        endTime,
        page: {
          pn: pageParam,
          ps: pageSize,
        },
      }

      const response = await walletService.getTransactionList(requestParams)
      return response
    },
    initialPageParam: 1,
    getNextPageParam: (lastPage) => {
      const { pageList } = lastPage
      if (!pageList) return undefined

      const { pn = 1, ps = pageSize, tc = 0 } = pageList
      const totalPages = Math.ceil(tc / ps)

      // 如果当前页小于总页数，返回下一页页码
      return pn < totalPages ? pn + 1 : undefined
    },
    enabled: tokenManager.isAuthenticated(),
    staleTime: 0, // 交易流水不缓存，每次都获取最新数据
  })
}

/**
 * 获取交易记录列表的完整 hook，包含上拉加载功能
 * 返回处理好的数据和加载状态
 */
export function useTransactionListWithInfiniteScroll(params: UseGetTransactionListParams = {}) {
  const infiniteQuery = useGetTransactionList(params)

  const {
    data,
    error,
    fetchNextPage,
    hasNextPage,
    isFetching,
    isFetchingNextPage,
    status,
    isLoading,
    isError,
    refetch,
  } = infiniteQuery

  // 扁平化所有页面的数据
  const allTransactions = data?.pages?.flatMap((page) => page.pageList?.datas || []) || []

  // 获取第一页的汇总信息
  const summary = data?.pages?.[0]
    ? {
        incomeTotal: data.pages[0].incomeTotal,
        outcomeTotal: data.pages[0].outcomeTotal,
      }
    : undefined

  // 总数据条数（从第一页获取）
  const totalCount = data?.pages?.[0]?.pageList?.tc || 0

  return {
    // 数据
    transactions: allTransactions,
    summary,
    totalCount,

    // 加载状态
    isLoading,
    isError,
    isFetching,
    isFetchingNextPage,
    error,
    status,

    // 分页控制
    hasNextPage: hasNextPage || false,
    fetchNextPage,

    // 刷新
    refetch,

    // 原始 infiniteQuery 对象，用于高级用法
    infiniteQuery,
  }
}
