library notifications_bloc;

import 'package:equatable/equatable.dart';
import 'package:injectable/injectable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:dio/dio.dart';
import '../../../../core/utils/logger.dart';
import '../../data/models/notification_model.dart';
import '../../data/repositories/notification_repository.dart';

part 'notifications_event.dart';
part 'notifications_state.dart';

@injectable
class NotificationsBloc extends Bloc<NotificationsEvent, NotificationsState> {
  final NotificationRepository _repository;

  NotificationsBloc(this._repository) : super(const NotificationsInitial()) {
    on<LoadNotifications>(_onLoadNotifications);
    on<MarkNotificationAsRead>(_onMarkAsRead);
    on<RefreshNotifications>(_onRefresh);
  }

  Future<void> _onLoadNotifications(
    LoadNotifications event,
    Emitter<NotificationsState> emit,
  ) async {
    try {
      emit(const NotificationsLoading());
      final notifications = (event.membreId != null && event.membreId!.isNotEmpty)
          ? await _repository.getNotificationsByMembre(event.membreId!)
          : await _repository.getMesNotifications();
      final nonLues = notifications.where((n) => !n.estLue).length;
      emit(NotificationsLoaded(notifications: notifications, nonLuesCount: nonLues));
    } on DioException catch (e) {
      emit(NotificationsError(_networkError(e)));
    } catch (e) {
      emit(NotificationsError('Erreur lors du chargement : $e'));
    }
  }

  Future<void> _onMarkAsRead(
    MarkNotificationAsRead event,
    Emitter<NotificationsState> emit,
  ) async {
    try {
      await _repository.marquerCommeLue(event.notificationId);
      final currentState = state;
      if (currentState is NotificationsLoaded) {
        final updated = currentState.notifications.map((n) {
          if (n.id == event.notificationId) {
            return NotificationModel(
              id: n.id,
              typeNotification: n.typeNotification,
              priorite: n.priorite,
              statut: 'LUE',
              sujet: n.sujet,
              corps: n.corps,
              dateEnvoiPrevue: n.dateEnvoiPrevue,
              dateEnvoi: n.dateEnvoi,
              dateLecture: DateTime.now(),
              donneesAdditionnelles: n.donneesAdditionnelles,
              membreId: n.membreId,
              organisationId: n.organisationId,
            );
          }
          return n;
        }).toList();
        final nonLues = updated.where((n) => !n.estLue).length;
        emit(NotificationMarkedAsRead(notifications: updated, nonLuesCount: nonLues));
      }
    } catch (e, st) {
      AppLogger.error('NotificationsBloc: marquer comme lu échoué', error: e, stackTrace: st);
      emit(NotificationsError('Impossible de marquer comme lu'));
    }
  }

  Future<void> _onRefresh(
    RefreshNotifications event,
    Emitter<NotificationsState> emit,
  ) async {
    add(LoadNotifications(membreId: event.membreId));
  }

  String _networkError(DioException e) {
    final code = e.response?.statusCode;
    if (code == 401) return 'Non autorisé.';
    if (code == 403) return 'Accès refusé.';
    if (code != null && code >= 500) return 'Erreur serveur.';
    return 'Erreur réseau. Vérifiez votre connexion.';
  }
}
