import 'dart:async';
import 'package:flutter/material.dart';

/// Service to monitor and track app lifecycle state changes
/// This helps detect when app goes to background/foreground
class AppLifecycleService with WidgetsBindingObserver {
  final _stateController = StreamController<AppLifecycleState>.broadcast();
  
  /// Stream of app lifecycle state changes
  Stream<AppLifecycleState> get appStateStream => _stateController.stream;
  
  AppLifecycleState _currentState = AppLifecycleState.resumed;
  
  /// Current app lifecycle state
  AppLifecycleState get currentState => _currentState;
  
  /// Check if app is currently active/visible
  bool get isAppActive => _currentState == AppLifecycleState.resumed;
  
  /// Check if app is in background or inactive
  bool get isAppInBackground => 
      _currentState == AppLifecycleState.paused || 
      _currentState == AppLifecycleState.inactive ||
      _currentState == AppLifecycleState.detached;
  
  /// Last time app was resumed
  DateTime? _lastResumedTime;
  DateTime? get lastResumedTime => _lastResumedTime;
  
  /// Last time app went to background
  DateTime? _lastPausedTime;
  DateTime? get lastPausedTime => _lastPausedTime;
  
  /// Duration app has been in current state
  Duration get timeInCurrentState {
    final referenceTime = _currentState == AppLifecycleState.resumed 
        ? _lastResumedTime 
        : _lastPausedTime;
    
    if (referenceTime == null) return Duration.zero;
    return DateTime.now().difference(referenceTime);
  }
  
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    _currentState = state;
    
    // Track timing
    if (state == AppLifecycleState.resumed) {
      _lastResumedTime = DateTime.now();
      debugPrint('📱 App RESUMED');
    } else if (state == AppLifecycleState.paused) {
      _lastPausedTime = DateTime.now();
      debugPrint('📱 App PAUSED/BACKGROUNDED');
    } else if (state == AppLifecycleState.inactive) {
      debugPrint('📱 App INACTIVE');
    } else if (state == AppLifecycleState.detached) {
      debugPrint('📱 App DETACHED');
    }
    
    _stateController.add(state);
  }
  
  /// Initialize the lifecycle observer
  void initialize() {
    WidgetsBinding.instance.addObserver(this);
    debugPrint('📱 AppLifecycleService initialized');
  }
  
  /// Clean up resources
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _stateController.close();
    debugPrint('📱 AppLifecycleService disposed');
  }
}


