import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../api/api_client_provider.dart';

part 'unread_notifier.g.dart';

@Riverpod(keepAlive: true)
class UnreadSessions extends _$UnreadSessions {
  Timer? _pollTimer;

  @override
  Map<String, int> build() {
    _startPolling();
    ref.onDispose(_stopPolling);
    return {};
  }

  void _startPolling() {
    _stopPolling();
    _fetchUnreadCounts();
    _pollTimer = Timer.periodic(const Duration(seconds: 15), (_) {
      _fetchUnreadCounts();
    });
  }

  void _stopPolling() {
    _pollTimer?.cancel();
    _pollTimer = null;
  }

  Future<void> _fetchUnreadCounts() async {
    try {
      final apiClient = ref.read(apiClientProvider);
      final response = await apiClient.get('/api/mitra/chat-requests/sessions/active-with-unread');
      final sessions = response['data'] as List<dynamic>;
      final counts = <String, int>{};
      for (final s in sessions) {
        final id = s['id'] as String;
        final count = s['unread_count'] as int? ?? 0;
        if (count > 0) counts[id] = count;
      }
      state = counts;
    } catch (_) {}
  }

  int get totalUnread => state.values.fold(0, (a, b) => a + b);

  void markSessionRead(String sessionId) {
    state = {...state}..remove(sessionId);
  }

  void refresh() => _fetchUnreadCounts();
}
