import 'package:dio/dio.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hoshan/core/utils/date_time.dart';
import 'package:hoshan/data/model/ai/chats_history_model.dart';
import 'package:hoshan/data/model/ai/chats_indates_model.dart';
import 'package:hoshan/data/repository/chatbot_repository.dart';

part 'chats_history_event.dart';
part 'chats_history_state.dart';

class ChatsHistoryBloc extends Bloc<ChatsHistoryEvent, ChatsHistoryState> {
  static List<ChatsIndatesModel> chatsInDates = [];
  static List<Chats> chats = [];
  static int page = 1;
  static int? lastPage;

  ChatsHistoryBloc() : super(ChatsHistoryInitial()) {
    List<ChatsIndatesModel> onOrganizeChats(List<Chats> items) {
      DateTime now = DateTimeUtils.getNow();
      DateTime today = DateTime(now.year, now.month, now.day);
      DateTime yesterday = today.subtract(const Duration(days: 1));
      DateTime sevenDaysAgo = today.subtract(const Duration(days: 7));

      Map<String, List<Chats>> categorizedItems = {
        "امروز": [],
        "دیروز": [],
        '‌هفته گذشته': [],
        'قدیمی‌ترها': [],
      };

      for (var item in items) {
        final d = DateTimeUtils.convertStringIsoToDate(item.createdAt!);
        DateTime itemDate = DateTime(d.year, d.month, d.day);

        if (itemDate == today) {
          categorizedItems["امروز"]!.add(item);
        } else if (itemDate == yesterday) {
          categorizedItems["دیروز"]!.add(item);
        } else if (itemDate.isAfter(sevenDaysAgo) &&
            itemDate.isBefore(yesterday)) {
          categorizedItems['‌هفته گذشته']!.add(item);
        } else {
          categorizedItems['قدیمی‌ترها']!.add(item);
        }
      }
      // Print results
      chatsInDates.clear();
      categorizedItems.forEach((key, value) {
        if (value.isNotEmpty) {
          chatsInDates.add(ChatsIndatesModel(title: key, chats: value));
        }
      });

      return chatsInDates;
    }

    on<ChatsHistoryEvent>((event, emit) async {
      if (event is GetAllChats) {
        if (page - 1 == lastPage) {
          return;
        }
        if (page == 1) {
          chats.clear();
          emit(ChatsHistoryInitial());
        } else {
          emit(ChatsHistoryLoading(chatsInDates: chatsInDates));
        }
        try {
          final response = await ChatbotRepository.getChats(
              type: event.type,
              page: page,
              search: event.search,
              date: event.date,
              archive: event.archive);
          page++;
          lastPage = response.lastPage;

          chats.addAll(response.chats!);
          onOrganizeChats(chats);

          emit(ChatsHistorySuccess(chatsInDates: chatsInDates));
        } on DioException catch (e) {
          emit(ChatsHistoryFail());
          if (kDebugMode) {
            print("Dio Error is : $e");
          }
        }
      }

      if (event is AddChat) {
        emit(ChatsHistoryInitial());

        if (chatsInDates.isNotEmpty) {
          chatsInDates.first.chats.insert(0, event.chats);
          emit(ChatsHistorySuccess(chatsInDates: chatsInDates));
        } else {
          chatsInDates
              .add(ChatsIndatesModel(title: 'امروز', chats: [event.chats]));
          emit(ChatsHistorySuccess(chatsInDates: chatsInDates));
        }
      }

      if (event is RemoveChat) {
        emit(ChatsHistoryInitial());

        try {
          if (event.withCall) {
            await ChatbotRepository.deleteChat(id: event.chats.id!);
          }
          int? index;
          int? mainIndex;
          for (var chatInDate in chatsInDates) {
            for (var chat in chatInDate.chats) {
              if (chat == event.chats) {
                index = chatInDate.chats.indexOf(chat);
                mainIndex = chatsInDates.indexOf(chatInDate);
              }
            }
          }
          if (mainIndex != null && index != null) {
            chatsInDates[mainIndex].chats.removeAt(index);
            if (chatsInDates[mainIndex].chats.isEmpty) {
              chatsInDates.removeAt(mainIndex);
            }
          }

          emit(ChatsHistorySuccess(chatsInDates: chatsInDates));
        } on DioException catch (e) {
          // emit(ChatsHistoryFail());
          if (kDebugMode) {
            print("Dio Error is : $e");
          }
        }
      }

      if (event is RemoveAll) {
        emit(ChatsHistoryInitial());

        try {
          await ChatbotRepository.deleteAllChats(archive: event.archive);
          chatsInDates.clear();

          emit(ChatsHistorySuccess(chatsInDates: chatsInDates));
        } on DioException catch (e) {
          // emit(ChatsHistoryFail());
          if (kDebugMode) {
            print("Dio Error is : $e");
          }
        }
      }

      if (event is RestartChatsHistory) {
        page = 1;
        lastPage = null;
        chats.clear();
        chatsInDates.clear();
        emit(ChatsHistoryInitial());
      }
    });
  }
}
