import 'dart:async';
import 'dart:developer';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:enaklo_pos/data/repositories/product/product_repository.dart';

class SyncManager {
  final ProductRepository _productRepository;
  final Connectivity _connectivity = Connectivity();

  Timer? _syncTimer;
  bool _isSyncing = false;
  StreamSubscription<List<ConnectivityResult>>? _connectivitySubscription;

  SyncManager(this._productRepository) {
    _startPeriodicSync();
    _listenToConnectivityChanges();
  }

  void _startPeriodicSync() {
    // Sync setiap 5 menit jika ada koneksi
    _syncTimer = Timer.periodic(Duration(minutes: 5), (timer) {
      _performBackgroundSync();
    });
  }

  void _listenToConnectivityChanges() {
    _connectivitySubscription = _connectivity.onConnectivityChanged.listen(
      (List<ConnectivityResult> results) {
        // Check if any connection is available
        final hasConnection =
            results.any((result) => result != ConnectivityResult.none);

        if (hasConnection) {
          log('Connection restored, starting background sync');
          _performBackgroundSync();
        } else {
          log('Connection lost');
        }
      },
    );
  }

  Future<void> _performBackgroundSync() async {
    if (_isSyncing) return;

    // Check current connectivity before syncing
    final connectivityResults = await _connectivity.checkConnectivity();
    final hasConnection =
        connectivityResults.any((result) => result != ConnectivityResult.none);

    if (!hasConnection) {
      log('No internet connection, skipping sync');
      return;
    }

    try {
      _isSyncing = true;
      log('Starting background sync');

      await _productRepository.refreshProducts();

      log('Background sync completed');
    } catch (e) {
      log('Background sync failed: $e');
    } finally {
      _isSyncing = false;
    }
  }

  // Public method untuk manual sync
  Future<void> performManualSync() async {
    await _performBackgroundSync();
  }

  void dispose() {
    _syncTimer?.cancel();
    _connectivitySubscription?.cancel();
  }
}
