import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:kasy_kit/core/states/user_state_notifier.dart';
import 'package:kasy_kit/core/theme/theme.dart';
import 'package:kasy_kit/features/notifications/repositories/notifications_repository.dart';

class BottomItemNotification extends ConsumerStatefulWidget {
  const BottomItemNotification({super.key});

  @override
  ConsumerState<ConsumerStatefulWidget> createState() =>
      _BottomItemNotificationState();
}

class _BottomItemNotificationState
    extends ConsumerState<BottomItemNotification> {
  Stream<int>? _count$;

  @override
  Widget build(BuildContext context) {
    final String? userId =
        ref.watch(userStateNotifierProvider).user.idOrNull;
    const icon = Icon(KasyIcons.notification);

    if (userId == null) {
      return icon;
    }

    _count$ ??= ref
        .read(notificationRepositoryProvider)
        .listenToUnreadNotificationsCount(userId);

    return StreamBuilder<int>(
      key: const ValueKey('notification-count'),
      stream: _count$,
      builder: (context, snapshot) {
        final count = snapshot.data ?? 0;
        if (count == 0) return icon;
        return Badge(
          backgroundColor: context.colors.error,
          textColor: context.colors.onPrimary,
          label: Text(count > 99 ? '99+' : '$count'),
          child: icon,
        );
      },
    );
  }
}
