import 'dart:async';
import 'package:flutter/foundation.dart';
import 'pending_action_check_service.dart';

/// 待办操作轮询回调
typedef PendingActionDetectedCallback = void Function();

/// 待办操作轮询服务
///
/// 用于在 App 启动后定时检查是否有新的待办操作。
///
/// 设计说明：
/// - App 启动时如果检测到待办，直接进入待办页面，不启动轮询
/// - App 启动时如果没有待办，启动轮询器定时检查（每 4 秒）
/// - 轮询检测到待办时，停止轮询并触发回调
/// - 待办完成后不会重启轮询（防止重入问题）
class PendingActionPollingService {
  final PendingActionCheckService _checkService;

  /// 轮询间隔（秒）
  static const int _pollingIntervalSeconds = 4;

  /// 轮询定时器
  Timer? _pollingTimer;

  /// 是否正在运行
  bool _isRunning = false;

  /// 检测到待办时的回调
  PendingActionDetectedCallback? _onPendingActionDetected;

  PendingActionPollingService({
    required PendingActionCheckService checkService,
  }) : _checkService = checkService;

  /// 是否正在运行
  bool get isRunning => _isRunning;

  /// 启动轮询
  ///
  /// [onPendingActionDetected] 检测到待办操作时的回调
  void start({required PendingActionDetectedCallback onPendingActionDetected}) {
    if (_isRunning) {
      debugPrint('[PendingActionPollingService] 轮询已在运行中，忽略重复启动');
      return;
    }

    _isRunning = true;
    _onPendingActionDetected = onPendingActionDetected;

    debugPrint('[PendingActionPollingService] 启动轮询，间隔: $_pollingIntervalSeconds 秒');

    _pollingTimer = Timer.periodic(
      const Duration(seconds: _pollingIntervalSeconds),
      (_) => _checkForPendingActions(),
    );
  }

  /// 停止轮询
  void stop() {
    if (!_isRunning) {
      return;
    }

    debugPrint('[PendingActionPollingService] 停止轮询');

    _pollingTimer?.cancel();
    _pollingTimer = null;
    _isRunning = false;
    _onPendingActionDetected = null;
  }

  /// 执行一次检查
  Future<void> _checkForPendingActions() async {
    if (!_isRunning) {
      return;
    }

    try {
      debugPrint('[PendingActionPollingService] 执行轮询检查...');

      final hasPending = await _checkService.hasPendingActions();

      if (hasPending && _isRunning) {
        debugPrint('[PendingActionPollingService] 检测到待办操作！停止轮询并触发回调');

        // 先停止轮询，防止重入
        final callback = _onPendingActionDetected;
        stop();

        // 触发回调
        callback?.call();
      } else {
        debugPrint('[PendingActionPollingService] 无待办操作');
      }
    } catch (e) {
      debugPrint('[PendingActionPollingService] 检查失败: $e');
      // 检查失败不停止轮询，继续下一次检查
    }
  }

  /// 释放资源
  void dispose() {
    stop();
  }
}
