import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { configsApi } from '../api/configs.api';
import { useToast } 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' });
    },
  });
}
