import { useEffect } from 'react';
import { useQuery, useMutation, useQueryClient, type UseQueryResult } from '@tanstack/react-query';
import {
  fetchSyncStats,
  fetchSyncHistory,
  fetchSyncHealth,
  fetchSendQueueSummary,
  fetchSyncThroughput,
  fetchFailedSends,
  retrySend,
  type SyncStats,
  type SyncHistoryRecord,
  type SyncHealthEntry,
  type SendQueueSummary,
  type SyncThroughput,
  type FailedSendItem,
} from '@/api/sync';
import { fetchDiagnostics, fetchActivity, type Diagnostics, type ActivityEntry } from '@/api/diagnostics';
import { REFRESH_INTERVAL, STALE_TIME, ALL_QUERY_KEYS } from './refreshConfig';

const DEFAULT_DEVICE_ID = 'default';

// Single shared interval — all queries refresh together.
export function useDashboardRefresh(): void {
  const queryClient = useQueryClient();
  useEffect(() => {
    const id = setInterval(() => {
      for (const key of ALL_QUERY_KEYS) {
        queryClient.invalidateQueries({ queryKey: key });
      }
    }, REFRESH_INTERVAL);
    return () => clearInterval(id);
  }, [queryClient]);
}

export function useSyncStats(): UseQueryResult<SyncStats> {
  return useQuery({
    queryKey: ['syncStats', DEFAULT_DEVICE_ID],
    queryFn: async () => fetchSyncStats(DEFAULT_DEVICE_ID),
    staleTime: STALE_TIME,
  });
}

export function useSyncHistory(limit = 20): UseQueryResult<SyncHistoryRecord[]> {
  return useQuery({
    queryKey: ['syncHistory', DEFAULT_DEVICE_ID, limit],
    queryFn: async () => fetchSyncHistory(DEFAULT_DEVICE_ID, limit),
    staleTime: STALE_TIME,
  });
}

export function useSyncHealth(): UseQueryResult<SyncHealthEntry[]> {
  return useQuery({
    queryKey: ['syncHealth'],
    queryFn: fetchSyncHealth,
    staleTime: STALE_TIME,
  });
}

export function useSendQueueSummary(): UseQueryResult<SendQueueSummary> {
  return useQuery({
    queryKey: ['sendQueueSummary'],
    queryFn: fetchSendQueueSummary,
    staleTime: STALE_TIME,
  });
}

export function useSyncThroughput(window = '24h'): UseQueryResult<SyncThroughput> {
  return useQuery({
    queryKey: ['syncThroughput', window],
    queryFn: async () => fetchSyncThroughput(window),
    staleTime: STALE_TIME,
  });
}

export function useDiagnostics(): UseQueryResult<Diagnostics> {
  return useQuery({
    queryKey: ['diagnostics'],
    queryFn: fetchDiagnostics,
    staleTime: STALE_TIME,
  });
}

export function useFailedSends(): UseQueryResult<FailedSendItem[]> {
  return useQuery({
    queryKey: ['failedSends'],
    queryFn: fetchFailedSends,
    staleTime: STALE_TIME,
  });
}

export function useActivity(): UseQueryResult<ActivityEntry[]> {
  return useQuery({
    queryKey: ['activity'],
    queryFn: fetchActivity,
    staleTime: STALE_TIME,
  });
}

export function useRetrySend() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => retrySend(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['sendQueueSummary'] });
      queryClient.invalidateQueries({ queryKey: ['failedSends'] });
    },
  });
}
