import 'dart:async';
import 'package:flutter/widgets.dart';
import '../services/notification_service.dart';

/// 未读通知徽章管理器
/// 使用 ValueNotifier 管理未读数量，与 LocaleManager 风格一致
class NotificationBadgeManager with WidgetsBindingObserver {
  static final NotificationBadgeManager _instance = NotificationBadgeManager._();
  factory NotificationBadgeManager() => _instance;
  NotificationBadgeManager._();

  final ValueNotifier<int> unreadCount = ValueNotifier<int>(0);

  Timer? _refreshTimer;
  NotificationService? _notificationService;
  bool _initialized = false;

  static const _refreshIntervalSeconds = 30;

  /// 初始化
  void initialize({NotificationService? notificationService}) {
    if (_initialized) return;
    _notificationService = notificationService ?? NotificationService();
    WidgetsBinding.instance.addObserver(this);
    _loadUnreadCount();
    _startAutoRefresh();
    _initialized = true;
  }

  /// 释放资源
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _refreshTimer?.cancel();
    _initialized = false;
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      _loadUnreadCount();
    }
  }

  void _startAutoRefresh() {
    _refreshTimer?.cancel();
    _refreshTimer = Timer.periodic(
      const Duration(seconds: _refreshIntervalSeconds),
      (_) => _loadUnreadCount(),
    );
  }

  Future<void> _loadUnreadCount() async {
    try {
      final notifCount = await _notificationService!.getUnreadCount();
      final announcementCount = await _notificationService!.getAnnouncementUnreadCount();
      unreadCount.value = notifCount + announcementCount;
    } catch (e) {
      debugPrint('[NotificationBadge] 加载未读数量失败: $e');
    }
  }

  /// 手动刷新
  Future<void> refresh() async {
    await _loadUnreadCount();
  }

  /// 减少未读数（标记单条已读后调用）
  void decrementCount() {
    if (unreadCount.value > 0) {
      unreadCount.value = unreadCount.value - 1;
    }
  }

  /// 清空未读数（全部标记已读后调用）
  void clearCount() {
    unreadCount.value = 0;
  }

  /// 设置具体数值
  void updateCount(int count) {
    unreadCount.value = count;
  }
}
