import 'package:flutter/foundation.dart';
import '../services/update_service.dart';
import '../services/storage_service.dart';

class UpdateProvider extends ChangeNotifier {
  final UpdateService _updateService = UpdateService();
  final StorageService _storageService = StorageService();
  
  UpdateInfo? _availableUpdate;
  bool _isChecking = false;
  DateTime? _lastChecked;
  bool _updateDismissed = false;
  
  UpdateInfo? get availableUpdate => _availableUpdate;
  bool get isChecking => _isChecking;
  DateTime? get lastChecked => _lastChecked;
  bool get hasUpdate => _availableUpdate != null && !_updateDismissed;
  
  /// Check for updates manually
  Future<void> checkForUpdates({bool force = false}) async {
    if (_isChecking) return;
    
    // Don't check too frequently unless forced
    if (!force && _lastChecked != null) {
      final timeSinceLastCheck = DateTime.now().difference(_lastChecked!);
      if (timeSinceLastCheck.inHours < 1) {
        if (kDebugMode) {
          print('Skipping update check - last checked ${timeSinceLastCheck.inMinutes} minutes ago');
        }
        return;
      }
    }
    
    _isChecking = true;
    notifyListeners();
    
    try {
      final updateInfo = await _updateService.checkForUpdates();
      _availableUpdate = updateInfo;
      _lastChecked = DateTime.now();
      _updateDismissed = false;
      
      // Save last check time
      await _storageService.setString('last_update_check', _lastChecked!.toIso8601String());
      
      if (updateInfo != null) {
        if (kDebugMode) {
          print('Update available: ${updateInfo.latestVersion}');
        }
        
        // Check if this version was already dismissed
        final dismissedVersion = await _storageService.getString('dismissed_update_version');
        if (dismissedVersion == updateInfo.latestVersion) {
          _updateDismissed = true;
        }
      }
    } catch (e) {
      if (kDebugMode) {
        print('Error checking for updates: $e');
      }
    } finally {
      _isChecking = false;
      notifyListeners();
    }
  }
  
  /// Dismiss the current update notification
  Future<void> dismissUpdate() async {
    if (_availableUpdate != null) {
      _updateDismissed = true;
      await _storageService.setString('dismissed_update_version', _availableUpdate!.latestVersion);
      notifyListeners();
    }
  }
  
  /// Initialize the provider and load saved state
  Future<void> initialize() async {
    // Load last check time
    final lastCheckString = await _storageService.getString('last_update_check');
    if (lastCheckString != null) {
      _lastChecked = DateTime.tryParse(lastCheckString);
    }
    
    // Check for updates on startup (but don't force it)
    await checkForUpdates();
  }
  
  /// Check for updates automatically in the background
  void startPeriodicChecks() {
    // Check every 4 hours
    Stream.periodic(const Duration(hours: 4)).listen((_) {
      checkForUpdates();
    });
  }
}