import 'package:cargocalculaterapp/constants/constants.dart';
import 'package:cargocalculaterapp/features/home/data/models/read_notification_request.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../data/models/notification_response.dart';
import '../../../domain/usecase/notification_read_usecase.dart';
import '../../../domain/usecase/notification_usecase.dart';

part 'notification_event.dart';

part 'notification_state.dart';

class NotificationBloc extends Bloc<NotificationEvent, NotificationState> {
  NotificationBloc(this.notificationUseCase, this.notificationReadUseCase)
    : super(
        const NotificationState(
          isLoading: false,
          currentPage: 1,
          paginationLoading: false,
        ),
      ) {
    on<GetNotificationsEvent>(_onGetNotifications);
    on<NotificationPaginationEvent>(_notificationPagination);
    on<ReadNotificationsEvent>(_notificationRead);
  }

  final NotificationUseCase notificationUseCase;
  final NotificationReadUseCase notificationReadUseCase;
  final Map<String, dynamic> notificationRequest = {};

  Future<void> _onGetNotifications(
    GetNotificationsEvent event,
    Emitter<NotificationState> emit,
  ) async {
    emit(state.copyWith(isLoading: true));
    notificationRequest[AppKeys.page] = 1;
    notificationRequest[AppKeys.limit] = AppConst.limit;

    final response = await notificationUseCase(notificationRequest);
    response.fold(
      (l) {
        emit(state.copyWith(isLoading: false));
      },
      (r) {
        add(ReadNotificationsEvent(notifications: r.notifications ?? []));
        emit(
          state.copyWith(
            isLoading: false,
            currentPage: 1,
            notifications: r.notifications,
            pageCount: ((r.totalCount ?? 1) / 20).ceil(),
          ),
        );
      },
    );
  }

  Future<void> _notificationPagination(
    NotificationPaginationEvent event,
    Emitter<NotificationState> emit,
  ) async {
    notificationRequest[AppKeys.page] = event.page;
    emit(state.copyWith(paginationLoading: true, currentPage: event.page));
    final response = await notificationUseCase(notificationRequest);
    response.fold(
      (l) {
        emit(state.copyWith(paginationLoading: false));
      },
      (r) {
        add(ReadNotificationsEvent(notifications: r.notifications ?? []));
        final List<Notifications> notifications = [];
        notifications.addAll(List.of(state.notifications ?? []));
        notifications.addAll(List.of(r.notifications ?? []));

        emit(
          state.copyWith(
            paginationLoading: false,
            pageCount: ((r.totalCount ?? 1) / 20).ceil(),
            notifications: notifications,
          ),
        );
      },
    );
  }

  Future<void> _notificationRead(
    ReadNotificationsEvent event,
    Emitter<NotificationState> emit,
  ) async {
    final List<String> ids = [];
    for (var element in event.notifications) {
      if (!(element.isRead ?? false)) {
        ids.add(element.id ?? "");
      }
    }
    if (ids.isNotEmpty) {
      await notificationReadUseCase(
        ReadNotificationRequest(notificationIds: ids),
      );
    }
  }
}
