// Offline/Online Network Hook

import { useState, useEffect, useCallback } from 'react';
import { hasLocalData, getAllLocalFeedItems, getLocalFeedItems, syncAllFeeds } from '@/services/sync-service';
import { FeedItem } from '@/types/feed';

type NetworkStatus = 'online' | 'offline' | 'unknown';

interface UseOfflineReturn {
  isOnline: boolean;
  networkStatus: NetworkStatus;
  hasOfflineData: boolean;
  isSyncing: boolean;
  lastSyncTime: Date | null;
  syncNow: () => Promise<void>;
  getOfflineFeedItems: (subscriptionId?: string, limit?: number, offset?: number) => Promise<FeedItem[]>;
}

export function useOffline(): UseOfflineReturn {
  const [networkStatus, setNetworkStatus] = useState<NetworkStatus>('unknown');
  const [hasOfflineData, setHasOfflineData] = useState(false);
  const [isSyncing, setIsSyncing] = useState(false);
  const [lastSyncTime, setLastSyncTime] = useState<Date | null>(null);

  // Check network status (simplified - in production would use @react-native-community/netinfo)
  const checkNetworkStatus = useCallback(async () => {
    try {
      // Try to fetch from a known endpoint to test connectivity
      const response = await fetch('https://www.google.com/favicon.ico', {
        method: 'HEAD',
        mode: 'no-cors',
      });
      setNetworkStatus('online');
      return true;
    } catch {
      setNetworkStatus('offline');
      return false;
    }
  }, []);

  // Check if we have offline data
  const checkOfflineData = useCallback(async () => {
    const hasData = await hasLocalData();
    setHasOfflineData(hasData);
    return hasData;
  }, []);

  // Sync now
  const syncNow = useCallback(async () => {
    if (networkStatus === 'offline') {
      console.log('[Offline] Cannot sync while offline');
      return;
    }

    setIsSyncing(true);
    try {
      await syncAllFeeds();
      setLastSyncTime(new Date());
      await checkOfflineData();
    } finally {
      setIsSyncing(false);
    }
  }, [networkStatus, checkOfflineData]);

  // Get offline feed items
  const getOfflineFeedItems = useCallback(async (
    subscriptionId?: string,
    limit: number = 50,
    offset: number = 0
  ): Promise<FeedItem[]> => {
    if (subscriptionId) {
      return getLocalFeedItems(subscriptionId, limit, offset);
    }
    return getAllLocalFeedItems(limit);
  }, []);

  // Initial checks
  useEffect(() => {
    checkNetworkStatus();
    checkOfflineData();

    // Periodic network check
    const interval = setInterval(() => {
      checkNetworkStatus();
    }, 30000); // Every 30 seconds

    return () => clearInterval(interval);
  }, [checkNetworkStatus, checkOfflineData]);

  return {
    isOnline: networkStatus === 'online',
    networkStatus,
    hasOfflineData,
    isSyncing,
    lastSyncTime,
    syncNow,
    getOfflineFeedItems,
  };
}