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/assistant_comments_model.dart';
import 'package:hoshan/data/repository/bot_repository.dart';

part 'assistant_comments_state.dart';

class AssistantCommentsCubit extends Cubit<AssistantCommentsState> {
  AssistantCommentsCubit() : super(AssistantCommentsInitial());
  static final List<AssistantComments> comments = [];

  void loadComments({required final int id}) async {
    int page = state.page;
    if (page == 1) {
      comments.clear();
    }
    int? lastPage = state.lastPage;
    if (lastPage != null && page > lastPage) {
      return;
    } else if (page != 1) {
      emit(AssistantCommentsLoading(
          comments: comments, lastPage: lastPage, page: page));
    }

    try {
      final cModel = await BotRepository.getAssistantComments(id, page);

      page++;
      lastPage = cModel.lastPage;
      comments.addAll(cModel.comments!);
      emit(AssistantCommentsSuccess(
          comments: comments, lastPage: lastPage, page: page));
    } on DioException catch (e) {
      emit(AssistantCommentsFail(
          comments: comments, lastPage: lastPage, page: page));
      if (kDebugMode) {
        print("Dio Error is : $e");
      }
    }
  }

  void addComment({required final AssistantComments comment}) {
    emit(AssistantCommentsLoading(
        comments: comments, lastPage: state.lastPage, page: state.page));
    comments.insert(0, comment);
    emit(AssistantCommentsSuccess(
        comments: comments, lastPage: state.lastPage, page: state.page));
  }

  void removeComment({required final String username}) {
    emit(AssistantCommentsLoading(
        comments: comments, lastPage: state.lastPage, page: state.page));

    comments.removeWhere(
      (element) => element.user!.username == username,
    );
    emit(AssistantCommentsSuccess(
        comments: comments, lastPage: state.lastPage, page: state.page));
  }

  // void changeComment({
  //   required final Comment newComment,
  // }) {
  //   emit(CommentsLoading(comments: comments));
  //   final index = comments.indexWhere(
  //     (element) => element.id == newComment.id,
  //   );
  //   comments[index] = newComment;
  //   emit(CommentsSuccess(comments: comments));
  // }

  // void addReplies({required final int commentId}) {
  //   emit(CommentsLoading(comments: comments));
  //   final comment = comments.firstWhere(
  //     (element) => element.id == commentId,
  //   );
  //   final index = comments.indexOf(comment);
  //   if (comment.replies == null) {
  //     comment.replies = 1;
  //   } else {
  //     comment.replies = comment.replies! + 1;
  //   }
  //   comments[index] = comment;
  //   emit(CommentsSuccess(comments: comments));
  // }
}
