import 'dart:async';
import 'package:flutter/widgets.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../di/injection_container.dart';
import '../services/notification_service.dart';
import '../../features/auth/presentation/providers/auth_provider.dart';

/// 未读通知数量状态
class NotificationBadgeState {
  final int unreadCount;
  final bool isLoading;

  const NotificationBadgeState({
    this.unreadCount = 0,
    this.isLoading = false,
  });

  NotificationBadgeState copyWith({
    int? unreadCount,
    bool? isLoading,
  }) {
    return NotificationBadgeState(
      unreadCount: unreadCount ?? this.unreadCount,
      isLoading: isLoading ?? this.isLoading,
    );
  }
}

/// 未读通知数量管理器
class NotificationBadgeNotifier extends StateNotifier<NotificationBadgeState>
    with WidgetsBindingObserver {
  final NotificationService _notificationService;
  final Ref _ref;
  Timer? _refreshTimer;

  /// 定时刷新间隔（30秒）
  static const _refreshIntervalSeconds = 30;

  NotificationBadgeNotifier(this._notificationService, this._ref)
      : super(const NotificationBadgeState()) {
    // 监听 App 生命周期
    WidgetsBinding.instance.addObserver(this);
    // 初始化时立即加载未读数量
    _loadUnreadCount();
    // 启动定时刷新
    _startAutoRefresh();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _refreshTimer?.cancel();
    super.dispose();
  }

  /// 监听 App 生命周期变化
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      // App 从后台切回前台，立即刷新
      debugPrint('[NotificationBadge] App 恢复前台，刷新未读数量');
      _loadUnreadCount();
    }
  }

  /// 启动自动刷新
  void _startAutoRefresh() {
    _refreshTimer?.cancel();
    _refreshTimer = Timer.periodic(
      const Duration(seconds: _refreshIntervalSeconds),
      (_) => _loadUnreadCount(),
    );
    debugPrint('[NotificationBadge] 自动刷新已启动 (间隔: ${_refreshIntervalSeconds}s)');
  }

  /// 停止自动刷新定时器（账号切换时调用，防止定时器在切换窗口期触发混账号请求）
  /// 调用后不会立即 dispose，invalidate Provider 时会重建并自动重启
  void stopAutoRefresh() {
    _refreshTimer?.cancel();
    _refreshTimer = null;
    debugPrint('[NotificationBadge] 自动刷新已停止（切换账号）');
  }

  /// 加载未读通知数量
  Future<void> _loadUnreadCount() async {
    try {
      final authState = _ref.read(authProvider);
      final userSerialNum = authState.userSerialNum;
      if (userSerialNum == null) {
        state = state.copyWith(unreadCount: 0);
        return;
      }

      state = state.copyWith(isLoading: true);

      final count = await _notificationService.getUnreadCount(
        userSerialNum: userSerialNum,
      );

      state = state.copyWith(
        unreadCount: count,
        isLoading: false,
      );

      debugPrint('[NotificationBadge] 未读通知数量: $count');
    } catch (e) {
      debugPrint('[NotificationBadge] 加载未读数量失败: $e');
      state = state.copyWith(isLoading: false);
    }
  }

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

  /// 更新未读数量（用于本地同步，如标记已读后）
  void updateCount(int count) {
    state = state.copyWith(unreadCount: count);
  }

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

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

/// 未读通知数量 Provider
final notificationBadgeProvider =
    StateNotifierProvider<NotificationBadgeNotifier, NotificationBadgeState>(
        (ref) {
  final notificationService = ref.watch(notificationServiceProvider);
  return NotificationBadgeNotifier(notificationService, ref);
});

/// 便捷 Provider: 只获取未读数量
final unreadNotificationCountProvider = Provider<int>((ref) {
  return ref.watch(notificationBadgeProvider).unreadCount;
});
