import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { configsApi } from '../api/configs.api';
import { useToast } from '@/lib/hooks/use-toast';
import { toast } from '@/lib/hooks/use-toast';

export function useConfigs() {
  return useQuery({
    queryKey: ['configs'],
    queryFn: () => configsApi.getAll(),
  });
}

export function useUpdateConfig() {
  const queryClient = useQueryClient();
  const { toast } = useToast();

  return useMutation({
    mutationFn: ({ key, value }: { key: string; value: string }) => configsApi.update(key, value),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['configs'] });
      toast({ title: '配置已更新', variant: 'success' as any });
    },
    onError: () => {
      toast({ title: '更新失败', variant: 'destructive' });
    },
  });
}

export function useTransferEnabled() {
  return useQuery({
    queryKey: ['configs', 'transfer-enabled'],
    queryFn: () => configsApi.getTransferEnabled(),
  });
}

export function useSetTransferEnabled() {
  const queryClient = useQueryClient();
  const { toast } = useToast();

  return useMutation({
    mutationFn: (enabled: boolean) => configsApi.setTransferEnabled(enabled),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['configs', 'transfer-enabled'] });
      toast({ title: '划转设置已更新', variant: 'success' as any });
    },
    onError: () => {
      toast({ title: '更新失败', variant: 'destructive' });
    },
  });
}

export function useMiningStatus() {
  return useQuery({
    queryKey: ['configs', 'mining-status'],
    queryFn: () => configsApi.getMiningStatus(),
    // 当算力未同步完成时，每 3 秒刷新一次；同步完成后每 30 秒刷新一次
    refetchInterval: (query) => {
      const data = query.state.data;
      if (data?.contributionSyncStatus && !data.contributionSyncStatus.isSynced) {
        return 3000; // 3 秒
      }
      return 30000; // 30 秒
    },
  });
}

export function useActivateMining() {
  const queryClient = useQueryClient();
  const { toast } = useToast();

  return useMutation({
    mutationFn: () => configsApi.activateMining(),
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['configs', 'mining-status'] });
      toast({ title: data.message || '挖矿已激活', variant: 'success' as any });
    },
    onError: () => {
      toast({ title: '激活失败', variant: 'destructive' });
    },
  });
}

export function useDeactivateMining() {
  const queryClient = useQueryClient();
  const { toast } = useToast();

  return useMutation({
    mutationFn: () => configsApi.deactivateMining(),
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['configs', 'mining-status'] });
      toast({ title: data.message || '挖矿已停用', variant: 'success' as any });
    },
    onError: () => {
      toast({ title: '停用失败', variant: 'destructive' });
    },
  });
}

export function useP2pTransferFee() {
  return useQuery({
    queryKey: ['configs', 'p2p-transfer-fee'],
    queryFn: () => configsApi.getP2pTransferFee(),
  });
}

export function useSetP2pTransferFee() {
  const queryClient = useQueryClient();
  const { toast } = useToast();

  return useMutation({
    mutationFn: ({ fee, minTransferAmount }: { fee: string; minTransferAmount: string }) =>
      configsApi.setP2pTransferFee(fee, minTransferAmount),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['configs', 'p2p-transfer-fee'] });
      toast({ title: 'P2P划转手续费配置已更新', variant: 'success' as any });
    },
    onError: (error: any) => {
      const message = error?.response?.data?.message || '更新失败';
      toast({ title: message, variant: 'destructive' });
    },
  });
}

export function usePoolAccounts() {
  return useQuery({
    queryKey: ['configs', 'pool-accounts'],
    queryFn: () => configsApi.getPoolAccounts(),
  });
}

export function usePoolAccountBalance(walletName: string) {
  return useQuery({
    queryKey: ['configs', 'pool-account', walletName],
    queryFn: () => configsApi.getPoolAccountBalance(walletName),
    refetchInterval: 30000,
    enabled: !!walletName,
  });
}

export function usePoolAccountBlockchainWithdraw() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ walletName, toAddress, amount }: { walletName: string; toAddress: string; amount: string }) =>
      configsApi.poolAccountBlockchainWithdraw(walletName, 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: ['configs', 'pool-account'] });
    },
    onError: (error: any) => {
      toast({ title: '错误', description: error.response?.data?.message || '区块链提现失败', variant: 'destructive' });
    },
  });
}

export function usePoolAccountCentralizedDeposit() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ walletName, amount }: { walletName: string; amount: string }) =>
      configsApi.poolAccountCentralizedDeposit(walletName, amount),
    onSuccess: (data) => {
      toast({ title: data.message || '充值成功' });
      queryClient.invalidateQueries({ queryKey: ['configs', 'pool-account'] });
    },
    onError: (error: any) => {
      toast({ title: '充值失败', description: error.response?.data?.message || '中心化充值失败', variant: 'destructive' });
    },
  });
}
