import type { AxiosError } from 'axios'

import { useMutation, useQuery, useQueryClient } from '@tanstack/vue-query'

import { useAxios } from '@/composables/use-axios'

// Types
export interface AdminLoginParams {
  username: string
  password: string
}

export interface AdminInfo {
  id: number
  username: string
  nickname: string
  role: number
  avatar?: string
}

export interface LoginResponse {
  token: string
  adminInfo: AdminInfo
}

export interface ApiResult<T> {
  code: string
  msg: string
  data: T
}

export interface User {
  id: number
  username: string
  nickname: string
  phone: string
  email: string
  status: number
  createTime: string
  updateTime: string
}

export interface Coin {
  id: number
  code: string
  name: string
  price: number
  priceType: number // 1: 实时 2: 手动
  status: number
  createTime: string
}

export interface OrderFund {
  id: number
  orderNo: string
  userId: number
  username: string
  type: number // 1: 充值 2: 提现
  amount: number
  status: number // 1: 待审批 2: 已通过 3: 已驳回
  createTime: string
  rejectReason?: string
  adminRemark?: string
}

export interface FinanceOverview {
  totalDeposit: number
  totalWithdraw: number
  fundBalance: number
  tradeValue: number
  pendingCount: number
  userCount: number
}

// Auth API
export function useAdminLoginMutation() {
  const { axiosInstance } = useAxios()

  return useMutation<ApiResult<LoginResponse>, AxiosError, AdminLoginParams>({
    mutationKey: ['useAdminLoginMutation'],
    mutationFn: async (params) => {
      const response = await axiosInstance.post('/admin/login', params)
      return response.data
    },
  })
}

// User Management API
export function useGetUserListQuery(params: { username?: string, status?: number, pageNum: number, pageSize: number }) {
  const { axiosInstance } = useAxios()

  return useQuery<ApiResult<{ list: User[], total: number }>, AxiosError>({
    queryKey: ['useGetUserListQuery', params],
    queryFn: async () => {
      const response = await axiosInstance.get('/admin/user/list', { params })
      return response.data
    },
  })
}

export function useGetUserDetailQuery(userId: number) {
  const { axiosInstance } = useAxios()

  return useQuery<ApiResult<any>, AxiosError>({
    queryKey: ['useGetUserDetailQuery', userId],
    queryFn: async () => {
      const response = await axiosInstance.get('/admin/user/detail', { params: { userId } })
      return response.data
    },
    enabled: !!userId,
  })
}

export function useUpdateUserStatusMutation() {
  const { axiosInstance } = useAxios()
  const queryClient = useQueryClient()

  return useMutation<ApiResult<void>, AxiosError, { userId: number, status: number }>({
    mutationKey: ['useUpdateUserStatusMutation'],
    mutationFn: async (params) => {
      const response = await axiosInstance.post('/admin/user/status', params)
      return response.data
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['useGetUserListQuery'] })
    },
  })
}

// Coin Management API
export function useGetCoinListQuery() {
  const { axiosInstance } = useAxios()

  return useQuery<ApiResult<{ list: Coin[] }>, AxiosError>({
    queryKey: ['useGetCoinListQuery'],
    queryFn: async () => {
      const response = await axiosInstance.get('/admin/coin/list')
      return response.data
    },
  })
}

export function useSaveCoinMutation() {
  const { axiosInstance } = useAxios()
  const queryClient = useQueryClient()

  return useMutation<ApiResult<void>, AxiosError, Coin>({
    mutationKey: ['useSaveCoinMutation'],
    mutationFn: async (coin) => {
      const response = await axiosInstance.post('/admin/coin/save', coin)
      return response.data
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['useGetCoinListQuery'] })
    },
  })
}

export function useUpdateCoinPriceMutation() {
  const { axiosInstance } = useAxios()
  const queryClient = useQueryClient()

  return useMutation<ApiResult<void>, AxiosError, { code: string, price: number }>({
    mutationKey: ['useUpdateCoinPriceMutation'],
    mutationFn: async (params) => {
      const response = await axiosInstance.post('/admin/coin/price', params)
      return response.data
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['useGetCoinListQuery'] })
    },
  })
}

export function useUpdateCoinStatusMutation() {
  const { axiosInstance } = useAxios()
  const queryClient = useQueryClient()

  return useMutation<ApiResult<void>, AxiosError, { coinId: number, status: number }>({
    mutationKey: ['useUpdateCoinStatusMutation'],
    mutationFn: async (params) => {
      const response = await axiosInstance.post('/admin/coin/status', params)
      return response.data
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['useGetCoinListQuery'] })
    },
  })
}

// Order Management API
export function useGetPendingOrdersQuery(params: { pageNum: number, pageSize: number }) {
  const { axiosInstance } = useAxios()

  return useQuery<ApiResult<{ list: OrderFund[], total: number }>, AxiosError>({
    queryKey: ['useGetPendingOrdersQuery', params],
    queryFn: async () => {
      const response = await axiosInstance.get('/admin/order/pending', { params })
      return response.data
    },
  })
}

export function useGetAllOrdersQuery(params: { type?: number, status?: number, pageNum: number, pageSize: number }) {
  const { axiosInstance } = useAxios()

  return useQuery<ApiResult<{ list: OrderFund[], total: number }>, AxiosError>({
    queryKey: ['useGetAllOrdersQuery', params],
    queryFn: async () => {
      const response = await axiosInstance.get('/admin/order/list', { params })
      return response.data
    },
  })
}

export function useApproveOrderMutation() {
  const { axiosInstance } = useAxios()
  const queryClient = useQueryClient()

  return useMutation<ApiResult<void>, AxiosError, { orderNo: string, status: number, rejectReason?: string, adminRemark?: string }>({
    mutationKey: ['useApproveOrderMutation'],
    mutationFn: async (params) => {
      const response = await axiosInstance.post('/admin/order/approve', params)
      return response.data
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['useGetPendingOrdersQuery'] })
      queryClient.invalidateQueries({ queryKey: ['useGetAllOrdersQuery'] })
    },
  })
}

// Finance Overview API
export function useGetFinanceOverviewQuery() {
  const { axiosInstance } = useAxios()

  return useQuery<ApiResult<FinanceOverview>, AxiosError>({
    queryKey: ['useGetFinanceOverviewQuery'],
    queryFn: async () => {
      const response = await axiosInstance.get('/admin/finance/overview')
      return response.data
    },
  })
}

// ========== 分析相关 API ==========

// 盈利分析
export function useGetProfitAnalysisQuery(range: string = 'month') {
  const { axiosInstance } = useAxios()

  return useQuery<ApiResult<{
    tradeFee: number
    tradeFeeRate: string
    fundFee: number
    fundFeeRate: string
    interestProfit: number
    interestRate: string
    totalProfit: number
  }>, AxiosError>({
    queryKey: ['useGetProfitAnalysisQuery', range],
    queryFn: async () => {
      const response = await axiosInstance.get('/admin/analysis/profit', { params: { range } })
      return response.data
    },
  })
}

// 资金流动趋势
export function useGetCashFlowTrendQuery(months: number = 6) {
  const { axiosInstance } = useAxios()

  return useQuery<ApiResult<Array<{
    month: string
    deposit: number
    withdraw: number
    netInflow: number
  }>>, AxiosError>({
    queryKey: ['useGetCashFlowTrendQuery', months],
    queryFn: async () => {
      const response = await axiosInstance.get('/admin/analysis/cash-flow', { params: { months } })
      return response.data
    },
  })
}

// 交易分析
export function useGetTradeAnalysisQuery(range: string = 'week') {
  const { axiosInstance } = useAxios()

  return useQuery<ApiResult<{
    buyAmount: number
    buyCount: number
    sellAmount: number
    sellCount: number
    netBuy: number
    trend: Array<{ date: string, buy: number, sell: number }>
  }>, AxiosError>({
    queryKey: ['useGetTradeAnalysisQuery', range],
    queryFn: async () => {
      const response = await axiosInstance.get('/admin/analysis/trade', { params: { range } })
      return response.data
    },
  })
}

// 币种交易分布
export function useGetCoinDistributionQuery(range: string = 'month') {
  const { axiosInstance } = useAxios()

  return useQuery<ApiResult<Array<{
    coinCode: string
    coinName: string
    amount: number
  }>>, AxiosError>({
    queryKey: ['useGetCoinDistributionQuery', range],
    queryFn: async () => {
      const response = await axiosInstance.get('/admin/analysis/coin-distribution', { params: { range } })
      return response.data
    },
  })
}

// 用户增长分析
export function useGetUserGrowthQuery(months: number = 6) {
  const { axiosInstance } = useAxios()

  return useQuery<ApiResult<{
    totalUsers: number
    monthNewUsers: number
    activeUsersToday: number
    trend: Array<{ month: string, newUsers: number, activeUsers: number }>
  }>, AxiosError>({
    queryKey: ['useGetUserGrowthQuery', months],
    queryFn: async () => {
      const response = await axiosInstance.get('/admin/analysis/user-growth', { params: { months } })
      return response.data
    },
  })
}

// 风险指标
export function useGetRiskMetricsQuery() {
  const { axiosInstance } = useAxios()

  return useQuery<ApiResult<{
    largeTransactions: number
    largeTransactionThreshold: string
    abnormalWithdrawals: number
    abnormalWithdrawalThreshold: string
    pendingKyc: number
    frozenAccounts: number
  }>, AxiosError>({
    queryKey: ['useGetRiskMetricsQuery'],
    queryFn: async () => {
      const response = await axiosInstance.get('/admin/analysis/risk')
      return response.data
    },
  })
}

// 健康度评分
export function useGetHealthScoreQuery() {
  const { axiosInstance } = useAxios()

  return useQuery<ApiResult<{
    overallScore: number
    liquidityScore: number
    riskScore: number
    stabilityScore: number
    grade: string
  }>, AxiosError>({
    queryKey: ['useGetHealthScoreQuery'],
    queryFn: async () => {
      const response = await axiosInstance.get('/admin/analysis/health')
      return response.data
    },
  })
}
