import 'package:bloc/bloc.dart';
import 'package:dio/dio.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/foundation.dart';
import 'package:hoshan/data/model/forum_model.dart';
import 'package:hoshan/data/repository/forum_repository.dart';
import 'package:hoshan/ui/screens/main/forum/cubit/comments_cubit.dart';

part 'replies_state.dart';

class RepliesCubit extends Cubit<RepliesState> {
  RepliesCubit() : super(RepliesInitial());

  void loadReplies({required final Comment comment}) async {
    int? lastPage = state.lastPage;
    int page = state.page;
    if (lastPage != null && page > lastPage) return;
    emit(
        RepliesLoading(replies: state.replies, lastPage: lastPage, page: page));
    try {
      final cModel = await ForumRepository.getForumCommentsReplies(
          id: comment.id!, categoryId: CommentsCubit.categoriesId, page: page);

      page++;
      lastPage = cModel.lastPage;
      final updatedList = List<Comment>.from(state.replies);
      updatedList.addAll(cModel.replies!);

      emit(
          RepliesSuccess(replies: updatedList, lastPage: lastPage, page: page));
    } on DioException catch (e) {
      emit(RepliesFail());
      if (kDebugMode) {
        print("Dio Error is : $e");
      }
    }
  }

  void clear() {
    emit(const RepliesSuccess(replies: [], lastPage: null, page: 1));
  }

  void addReply(
      {required final Comment comment, required final Comment parent}) {
    emit(RepliesLoading(
        replies: state.replies, lastPage: state.lastPage, page: state.page));
    final updatedList = List<Comment>.from(state.replies);
    if (updatedList.contains(parent)) {
      final index = updatedList.indexOf(parent);
      if (updatedList[index] == updatedList.last) {
        updatedList.add(comment);
      } else {
        updatedList.insert(index + 1, comment);
      }
    } else {
      updatedList.insert(0, comment);
    }

    emit(RepliesSuccess(
        replies: updatedList, lastPage: state.lastPage, page: state.page));
  }
}
