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/ai/messages_model.dart';
import 'package:hoshan/data/repository/chatbot_repository.dart';

part 'messages_event.dart';
part 'messages_state.dart';

class MessagesBloc extends Bloc<MessagesEvent, MessagesState> {
  MessagesBloc() : super(MessagesInitial()) {
    on<MessagesEvent>((event, emit) async {
      if (event is GetallMessages) {
        emit(MessagesLoading());
        try {
          final response =
              await ChatbotRepository.getMessages(id: event.chatId);
          final updatedList = List<Messages>.from(response.messages!);
          for (var i = 0; i < updatedList.length; i++) {
            try {
              updatedList[i].query = updatedList[i]
                  .content
                  ?.firstWhere(
                    (element) => element.type == 'text',
                  )
                  .text;
              if (updatedList[i].fromBot! && i > 0) {
                if (!updatedList[i - 1].fromBot!) {
                  updatedList[i].query = updatedList[i - 1]
                      .content
                      ?.firstWhere(
                        (element) => element.type == 'text',
                      )
                      .text;
                }
              }
            } catch (e) {
              if (kDebugMode) {
                print('Query Error is: $e');
              }
            }
          }
          if (updatedList.isEmpty) {
            emit(MessagesEmpty());
          } else {
            emit(MessagesSuccess(
                isGetAll: true,
                messages: updatedList)); // Copy the current state
          }
        } on DioException catch (e) {
          emit(MessagesFail());
          if (kDebugMode) {
            print("Dio Error is : $e");
          }
        }
      }
      if (event is AddMessage) {
        final updatedList = List<Messages>.from(state.messages);
        updatedList.add(event.message);
        if (kDebugMode) {
          print('📨 AddMessage: Total messages = ${updatedList.length}, Role = ${event.message.role}, File = ${event.message.file?.name}');
        }
        emit(MessagesSuccess(messages: updatedList)); // Copy the current state
      }

      if (event is RemoveInError) {
        final updatedList = List<Messages>.from(state.messages);
        updatedList.removeLast();
        updatedList.removeLast();

        emit(MessagesSuccess(messages: updatedList)); // Copy the current state
      }

      if (event is ChangeMessage) {
        final updatedList = List<Messages>.from(state.messages);

        final index = updatedList.indexOf(event.oldMessage);
        updatedList[index] = event.newMessage;

        emit(MessagesSuccess(messages: updatedList)); // Copy the current state
      }

      if (event is DeleteMessage) {
        try {
          if (event.chatId != null) {
            await ChatbotRepository.deleteMessage(
                chatId: event.chatId!, messageId: event.message.id!);
          }

          final updatedList = List<Messages>.from(state.messages);

          updatedList.remove(event.message);
          if (updatedList.isEmpty) {
            emit(MessagesEmpty());
          } else {
            emit(MessagesSuccess(messages: updatedList));
          }
        } catch (e) {
          if (kDebugMode) {
            print("Dio Error is : $e");
          }
        }
      }
      if (event is DeleteMessageWithId) {
        try {
          final updatedList = List<Messages>.from(state.messages);

          updatedList.removeWhere(
            (element) {
              return element.id == event.messageId;
            },
          );
          if (updatedList.isEmpty) {
            emit(MessagesEmpty());
          } else {
            emit(MessagesSuccess(messages: updatedList));
          }
        } catch (e) {
          if (kDebugMode) {
            print("Dio Error is : $e");
          }
        }
      }
      if (event is ResetMessages) {
        emit(MessagesInitial());
      }
    });
  }
}
