import 'package:flutter/material.dart';
import 'cache_service.dart';
import 'post_service.dart';
import 'invitations_service.dart';
import 'user_service.dart';

class AppLifecycleService extends WidgetsBindingObserver {
  static final AppLifecycleService _instance = AppLifecycleService._internal();
  factory AppLifecycleService() => _instance;
  AppLifecycleService._internal();

  bool _isInitialized = false;

  /// Initialize the app lifecycle service
  static void initialize() {
    if (!_instance._isInitialized) {
      WidgetsBinding.instance.addObserver(_instance);
      _instance._isInitialized = true;
      
      // DO NOT start polling automatically - only when user is logged in and on main screen
    }
  }

  /// Start all polling services (call this only when user is logged in and on main tabs)
  static void startAllPolling() {
    PostService.startPolling();
    InvitationsService.startPolling();
    UserService.startPolling();
  }

  /// Dispose the app lifecycle service
  static void dispose() {
    if (_instance._isInitialized) {
      WidgetsBinding.instance.removeObserver(_instance);
      _instance._isInitialized = false;
      
      // Stop all polling
      CacheService.stopAllPolling();
    }
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    
    switch (state) {
      case AppLifecycleState.resumed:
        _onAppResumed();
        break;
      case AppLifecycleState.paused:
        _onAppPaused();
        break;
      case AppLifecycleState.inactive:
        // App is transitioning, do nothing
        break;
      case AppLifecycleState.detached:
        _onAppDetached();
        break;
      case AppLifecycleState.hidden:
        // App is hidden, treat similar to paused
        break;
    }
  }

  void _onAppResumed() {
    // Only restart polling if it was already running (user is logged in)
    if (PostService.isPollingActive || InvitationsService.isPollingActive || UserService.isPollingActive) {
      print('App resumed - restarting polling');
      PostService.startPolling();
      InvitationsService.startPolling();
      UserService.startPolling();
    }
  }

  void _onAppPaused() {
    print('App paused - stopping polling');
    // Stop polling to save battery when app goes to background
    CacheService.stopAllPolling();
  }

  void _onAppDetached() {
    print('App detached - cleaning up');
    // Clean up when app is completely terminated
    CacheService.stopAllPolling();
    CacheService.clearAll();
  }

  /// Force refresh all cached data (useful for pull-to-refresh)
  static Future<void> refreshAllData() async {
    await Future.wait([
      PostService.getAllPosts(forceRefresh: true),
      InvitationsService.getAllInvitations(forceRefresh: true),
      UserService.getCurrentUser(forceRefresh: true),
    ]);
  }

  /// Get cache status for debugging
  static Map<String, dynamic> getCacheStatus() {
    return CacheService.getCacheInfo();
  }
}