import { useEffect, useRef } from 'react';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { setOnlineStatus } from '@/store/slices/networkSlice';

export function useBackgroundSync() {
  const dispatch = useAppDispatch();
  const { isOnline } = useAppSelector((state) => state.network);
  const { pendingActions } = useAppSelector((state) => state.offline);
  const syncIntervalRef = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {
    // Register background sync if supported
    if ('serviceWorker' in navigator && 'sync' in ServiceWorkerRegistration.prototype) {
      navigator.serviceWorker.ready.then((registration) => {
        // Register a sync event
        return (registration as any).sync.register('sync-pending-actions');
      }).catch((error) => {
        console.error('Background sync registration failed:', error);
      });
    }

    // Listen for sync events
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.addEventListener('message', (event) => {
        if (event.data && event.data.type === 'BACKGROUND_SYNC') {
          // Trigger sync from service worker by simulating online status
          dispatch(setOnlineStatus(true));
        }
      });
    }
  }, [dispatch]);

  useEffect(() => {
    // Periodic sync every 5 minutes when online and have pending actions
    if (isOnline && pendingActions.length > 0) {
      syncIntervalRef.current = setInterval(() => {
        console.log('Periodic sync check...');
        // Trigger sync by re-dispatching online status
        dispatch(setOnlineStatus(true));
      }, 5 * 60 * 1000); // 5 minutes
    }

    return () => {
      if (syncIntervalRef.current) {
        clearInterval(syncIntervalRef.current);
      }
    };
  }, [isOnline, pendingActions.length, dispatch]);

  // Sync on visibility change (when user returns to tab)
  useEffect(() => {
    const handleVisibilityChange = () => {
      if (document.visibilityState === 'visible' && isOnline && pendingActions.length > 0) {
        console.log('Tab visible, syncing pending actions...');
        // Trigger sync by re-dispatching online status
        dispatch(setOnlineStatus(true));
      }
    };

    document.addEventListener('visibilitychange', handleVisibilityChange);

    return () => {
      document.removeEventListener('visibilitychange', handleVisibilityChange);
    };
  }, [isOnline, pendingActions.length, dispatch]);

  return {
    pendingCount: pendingActions.length,
    isOnline,
  };
}
