import 'package:flutter/material.dart';
import 'package:em2rp/services/alert_service.dart';
import 'package:em2rp/providers/local_user_provider.dart';
import 'package:provider/provider.dart';

/// Badge de notifications dans l'AppBar
class NotificationBadge extends StatelessWidget {
  const NotificationBadge({super.key});

  @override
  Widget build(BuildContext context) {
    final localUserProvider = context.watch<LocalUserProvider>();
    final userId = localUserProvider.currentUser?.uid;

    if (userId == null) {
      return const SizedBox.shrink();
    }

    return StreamBuilder<int>(
      stream: AlertService().unreadCountStreamForUser(userId),
      builder: (context, snapshot) {
        final count = snapshot.data ?? 0;

        return Badge(
          label: Text('$count'),
          isLabelVisible: count > 0,
          backgroundColor: Colors.red,
          textColor: Colors.white,
          child: IconButton(
            icon: const Icon(Icons.notifications),
            onPressed: () => _openAlertsPage(context),
            tooltip: 'Notifications',
          ),
        );
      },
    );
  }

  void _openAlertsPage(BuildContext context) {
    Navigator.of(context).pushNamed('/alerts');
  }
}

