import 'dart:async';


class QuotationAutoRefreshController {
  bool _enabled = true;
  Timer? _timer;
  DateTime? _scheduledAt;
  DateTime? _triggeredAt;

  void setEnabled(bool enabled) {
    if (_enabled == enabled) return;
    _enabled = enabled;
  }

  void sync({
    required bool isLoading,
    required bool canRefresh,
    required DateTime? expiresAt,
    required Future<void> Function() onRefresh,
  }) {
    if (!_enabled || isLoading || !canRefresh) {
      _clearTimer();
      _scheduledAt = null;
      _triggeredAt = null;
      return;
    }

    if (expiresAt == null) {
      _clearTimer();
      _scheduledAt = null;
      _triggeredAt = null;
      return;
    }

    final delay = expiresAt.difference(DateTime.now().toUtc());
    if (delay <= Duration.zero) {
      if (_triggeredAt != null && _triggeredAt!.isAtSameMomentAs(expiresAt)) {
        return;
      }
      _triggeredAt = expiresAt;
      _clearTimer();
      onRefresh();
      return;
    }

    if (_scheduledAt != null &&
        _scheduledAt!.isAtSameMomentAs(expiresAt) &&
        _timer?.isActive == true) {
      return;
    }

    _triggeredAt = null;
    _clearTimer();
    _scheduledAt = expiresAt;
    _timer = Timer(delay, () {
      onRefresh();
    });
  }

  void reset() {
    _enabled = false;
    _scheduledAt = null;
    _triggeredAt = null;
    _clearTimer();
  }

  void dispose() {
    _clearTimer();
  }

  void _clearTimer() {
    _timer?.cancel();
    _timer = null;
  }
}
