import { useEffect, useState } from 'react';
import { offlineSyncManager } from '../lib/offlineSync';
import { useNetworkStore } from '../stores/networkStore';
import { useQueryClient } from '@tanstack/react-query';

export function useOfflineSync() {
  const { isOnline, updatePendingCount } = useNetworkStore();
  const queryClient = useQueryClient();
  const [lastSyncTime, setLastSyncTime] = useState<Date | null>(null);

  useEffect(() => {
    const unsubscribe = offlineSyncManager.onNetworkChange(async (online) => {
      if (online) {
        // Refetch all queries when coming back online
        await queryClient.refetchQueries();
        setLastSyncTime(new Date());
      }
      updatePendingCount();
    });

    return unsubscribe;
  }, [queryClient, updatePendingCount]);

  const manualSync = async () => {
    if (isOnline) {
      await offlineSyncManager.syncAll();
      await queryClient.refetchQueries();
      setLastSyncTime(new Date());
      updatePendingCount();
    }
  };

  return {
    isOnline,
    pendingCount: offlineSyncManager.getPendingCount(),
    lastSyncTime,
    manualSync,
  };
}
