import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../../../router/app_routes.dart';
import '../../../data/models/comment_request.dart';
import '../../../domain/usecase/comment_usecase.dart';

part 'comment_event.dart';

part 'comment_state.dart';

class CommentBloc extends Bloc<CommentEvent, CommentState> {
  CommentBloc(this.commentUseCase)
    : super(const CommentState(rating: 0, isLoading: false)) {
    on<RatingChangedEvent>(_ratingChange);
    on<CommentEnterEvent>(_commentEnter);
    on<SubmitEvent>(_commentSubmit);
  }

  final CommentUseCase commentUseCase;

  void _ratingChange(RatingChangedEvent event, Emitter<CommentState> emit) {
    emit(state.copyWith(rating: event.rating));
  }

  void _commentEnter(CommentEnterEvent event, Emitter<CommentState> emit) {
    emit(state.copyWith(comment: event.comment));
  }

  Future<void> _commentSubmit(
    SubmitEvent event,
    Emitter<CommentState> emit,
  ) async {
    emit(state.copyWith(isLoading: true));
    final response = await commentUseCase(
      CommentRequest(
        orderNumber: event.orderId,
        rate: state.rating.toInt(),
        message: state.comment,
      ),
    );
    response.fold(
      (l) {
        emit(state.copyWith(isLoading: false));
      },
      (r) {
        emit(state.copyWith(isLoading: false));
        Navigator.pop(rootNavigatorKey.currentContext!);
      },
    );
  }
}
