import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { marketMakerApi } from '../api/market-maker.api';
import { toast } from '@/lib/hooks/use-toast';

const MARKET_MAKER_NAME = 'MAIN_MARKET_MAKER';

export function useMarketMakerConfig() {
  return useQuery({
    queryKey: ['marketMaker', 'config', MARKET_MAKER_NAME],
    queryFn: () => marketMakerApi.getConfig(MARKET_MAKER_NAME),
    refetchInterval: 10000,
  });
}

export function useInitializeMarketMaker() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (data: {
      accountSequence: string;
      initialCash?: string;
      maxBuyRatio?: number;
    }) => marketMakerApi.initialize({ ...data, name: MARKET_MAKER_NAME }),
    onSuccess: (data) => {
      toast({ title: '成功', description: data.message });
      queryClient.invalidateQueries({ queryKey: ['marketMaker'] });
    },
    onError: (error: any) => {
      toast({ title: '错误', description: error.response?.data?.message || '初始化失败', variant: 'destructive' });
    },
  });
}

export function useUpdateMarketMakerConfig() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (data: {
      maxBuyRatio?: number;
      minIntervalMs?: number;
      maxIntervalMs?: number;
      priceStrategy?: string;
      discountRate?: number;
      kavaWalletAddress?: string;
      eusdtWalletAddress?: string;
    }) => marketMakerApi.updateConfig(MARKET_MAKER_NAME, data),
    onSuccess: (data) => {
      toast({ title: '成功', description: data.message });
      queryClient.invalidateQueries({ queryKey: ['marketMaker'] });
    },
    onError: (error: any) => {
      toast({ title: '错误', description: error.response?.data?.message || '更新失败', variant: 'destructive' });
    },
  });
}

export function useDepositCash() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ amount, memo }: { amount: string; memo?: string }) =>
      marketMakerApi.deposit(MARKET_MAKER_NAME, amount, memo),
    onSuccess: (data) => {
      toast({ title: '成功', description: data.message });
      queryClient.invalidateQueries({ queryKey: ['marketMaker'] });
    },
    onError: (error: any) => {
      toast({ title: '错误', description: error.response?.data?.message || '充值失败', variant: 'destructive' });
    },
  });
}

export function useWithdrawCash() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ amount, memo }: { amount: string; memo?: string }) =>
      marketMakerApi.withdraw(MARKET_MAKER_NAME, amount, memo),
    onSuccess: (data) => {
      toast({ title: '成功', description: data.message });
      queryClient.invalidateQueries({ queryKey: ['marketMaker'] });
    },
    onError: (error: any) => {
      toast({ title: '错误', description: error.response?.data?.message || '提现失败', variant: 'destructive' });
    },
  });
}

export function useDepositShares() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ amount, memo }: { amount: string; memo?: string }) =>
      marketMakerApi.depositShares(MARKET_MAKER_NAME, amount, memo),
    onSuccess: (data) => {
      toast({ title: '成功', description: data.message });
      queryClient.invalidateQueries({ queryKey: ['marketMaker'] });
    },
    onError: (error: any) => {
      toast({ title: '错误', description: error.response?.data?.message || '充值失败', variant: 'destructive' });
    },
  });
}

export function useWithdrawShares() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ amount, memo }: { amount: string; memo?: string }) =>
      marketMakerApi.withdrawShares(MARKET_MAKER_NAME, amount, memo),
    onSuccess: (data) => {
      toast({ title: '成功', description: data.message });
      queryClient.invalidateQueries({ queryKey: ['marketMaker'] });
    },
    onError: (error: any) => {
      toast({ title: '错误', description: error.response?.data?.message || '提现失败', variant: 'destructive' });
    },
  });
}

// 区块链提现
export function useBlockchainWithdrawCash() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ toAddress, amount }: { toAddress: string; amount: string }) =>
      marketMakerApi.blockchainWithdrawCash(MARKET_MAKER_NAME, toAddress, amount),
    onSuccess: (data) => {
      if (data.success) {
        toast({
          title: '区块链提现成功',
          description: `交易哈希: ${data.txHash?.slice(0, 20)}...`,
        });
      } else {
        toast({ title: '提现失败', description: data.error || data.message, variant: 'destructive' });
      }
      queryClient.invalidateQueries({ queryKey: ['marketMaker'] });
    },
    onError: (error: any) => {
      toast({ title: '错误', description: error.response?.data?.message || '区块链提现失败', variant: 'destructive' });
    },
  });
}

export function useBlockchainWithdrawShares() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ toAddress, amount }: { toAddress: string; amount: string }) =>
      marketMakerApi.blockchainWithdrawShares(MARKET_MAKER_NAME, toAddress, amount),
    onSuccess: (data) => {
      if (data.success) {
        toast({
          title: '区块链提现成功',
          description: `交易哈希: ${data.txHash?.slice(0, 20)}...`,
        });
      } else {
        toast({ title: '提现失败', description: data.error || data.message, variant: 'destructive' });
      }
      queryClient.invalidateQueries({ queryKey: ['marketMaker'] });
    },
    onError: (error: any) => {
      toast({ title: '错误', description: error.response?.data?.message || '区块链提现失败', variant: 'destructive' });
    },
  });
}

export function useStartTaker() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: () => marketMakerApi.start(MARKET_MAKER_NAME),
    onSuccess: (data) => {
      toast({ title: '成功', description: data.message });
      queryClient.invalidateQueries({ queryKey: ['marketMaker'] });
    },
    onError: (error: any) => {
      toast({ title: '错误', description: error.response?.data?.message || '启动失败', variant: 'destructive' });
    },
  });
}

export function useStopTaker() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: () => marketMakerApi.stop(MARKET_MAKER_NAME),
    onSuccess: (data) => {
      toast({ title: '成功', description: data.message });
      queryClient.invalidateQueries({ queryKey: ['marketMaker'] });
    },
    onError: (error: any) => {
      toast({ title: '错误', description: error.response?.data?.message || '停止失败', variant: 'destructive' });
    },
  });
}

export function useTakeOrder() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: () => marketMakerApi.takeOrder(MARKET_MAKER_NAME),
    onSuccess: (data) => {
      if (data.success && data.tradeInfo) {
        toast({
          title: '吃单成功',
          description: `成交价格: ${data.tradeInfo.price}, 数量: ${data.tradeInfo.quantity}`,
        });
      } else {
        toast({ title: '提示', description: data.message });
      }
      queryClient.invalidateQueries({ queryKey: ['marketMaker'] });
    },
    onError: (error: any) => {
      toast({ title: '错误', description: error.response?.data?.message || '吃单失败', variant: 'destructive' });
    },
  });
}

export function useStartMaker() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: () => marketMakerApi.startMaker(MARKET_MAKER_NAME),
    onSuccess: (data) => {
      toast({ title: '成功', description: data.message });
      queryClient.invalidateQueries({ queryKey: ['marketMaker'] });
    },
    onError: (error: any) => {
      toast({ title: '错误', description: error.response?.data?.message || '启动失败', variant: 'destructive' });
    },
  });
}

export function useStopMaker() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: () => marketMakerApi.stopMaker(MARKET_MAKER_NAME),
    onSuccess: (data) => {
      toast({ title: '成功', description: data.message });
      queryClient.invalidateQueries({ queryKey: ['marketMaker'] });
    },
    onError: (error: any) => {
      toast({ title: '错误', description: error.response?.data?.message || '停止失败', variant: 'destructive' });
    },
  });
}

export function useRefreshOrders() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: () => marketMakerApi.refreshOrders(MARKET_MAKER_NAME),
    onSuccess: (data) => {
      if (data.success) {
        toast({
          title: '刷新成功',
          description: `买单: ${data.bidOrders || 0}, 卖单: ${data.askOrders || 0}`,
        });
      } else {
        toast({ title: '提示', description: data.message });
      }
      queryClient.invalidateQueries({ queryKey: ['marketMaker'] });
    },
    onError: (error: any) => {
      toast({ title: '错误', description: error.response?.data?.message || '刷新失败', variant: 'destructive' });
    },
  });
}

export function useCancelAllOrders() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: () => marketMakerApi.cancelAllOrders(MARKET_MAKER_NAME),
    onSuccess: (data) => {
      toast({ title: '成功', description: `已取消 ${data.cancelledCount} 个挂单` });
      queryClient.invalidateQueries({ queryKey: ['marketMaker'] });
    },
    onError: (error: any) => {
      toast({ title: '错误', description: error.response?.data?.message || '取消失败', variant: 'destructive' });
    },
  });
}

export function useUpdateMakerConfig() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (data: {
      bidEnabled?: boolean;
      bidLevels?: number;
      bidSpread?: number;
      bidLevelSpacing?: number;
      bidQuantityPerLevel?: string;
      askEnabled?: boolean;
      askLevels?: number;
      askSpread?: number;
      askLevelSpacing?: number;
      askQuantityPerLevel?: string;
      refreshIntervalMs?: number;
    }) => marketMakerApi.updateMakerConfig(MARKET_MAKER_NAME, data),
    onSuccess: (data) => {
      toast({ title: '成功', description: data.message });
      queryClient.invalidateQueries({ queryKey: ['marketMaker'] });
    },
    onError: (error: any) => {
      toast({ title: '错误', description: error.response?.data?.message || '更新失败', variant: 'destructive' });
    },
  });
}

export function useMakerOrders(params?: {
  side?: 'BID' | 'ASK';
  status?: 'ACTIVE' | 'FILLED' | 'CANCELLED';
  page?: number;
  pageSize?: number;
}) {
  return useQuery({
    queryKey: ['marketMaker', 'orders', MARKET_MAKER_NAME, params],
    queryFn: () => marketMakerApi.getMakerOrders(MARKET_MAKER_NAME, params),
    refetchInterval: 10000,
  });
}

export function useDepth(levels?: number) {
  return useQuery({
    queryKey: ['marketMaker', 'depth', levels],
    queryFn: () => marketMakerApi.getDepth(levels),
    refetchInterval: 5000,
  });
}

export function useMarketMakerStats() {
  return useQuery({
    queryKey: ['marketMaker', 'stats', MARKET_MAKER_NAME],
    queryFn: () => marketMakerApi.getStats(MARKET_MAKER_NAME),
    refetchInterval: 10000,
  });
}

export function useCashDepositLedgers(page: number = 1, pageSize: number = 20) {
  return useQuery({
    queryKey: ['marketMaker', 'ledgers', 'cash-deposit', MARKET_MAKER_NAME, page, pageSize],
    queryFn: () =>
      marketMakerApi.getLedgers(MARKET_MAKER_NAME, {
        type: 'DEPOSIT',
        assetType: 'CASH',
        page,
        pageSize,
      }),
  });
}

export function useDepthEnabled() {
  return useQuery({
    queryKey: ['trading', 'depthEnabled'],
    queryFn: () => marketMakerApi.getDepthEnabled(),
  });
}

export function useSetDepthEnabled() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (enabled: boolean) => marketMakerApi.setDepthEnabled(enabled),
    onSuccess: (data) => {
      toast({ title: '成功', description: data.message });
      queryClient.invalidateQueries({ queryKey: ['trading', 'depthEnabled'] });
    },
    onError: (error: any) => {
      toast({ title: '错误', description: error.response?.data?.message || '设置失败', variant: 'destructive' });
    },
  });
}
