import 'dart:async';

import 'package:didvan/main.dart';
import 'package:didvan/models/ai/bots_model.dart';
import 'package:didvan/models/ai/chats_model.dart';
import 'package:didvan/models/enums.dart';
import 'package:didvan/models/view/alert_data.dart';
import 'package:didvan/providers/core.dart';
import 'package:didvan/services/network/request.dart';
import 'package:didvan/services/network/request_helper.dart';
import 'package:didvan/utils/action_sheet.dart';

class HistoryAiChatState extends CoreProvier {
  final List<ChatsModel> chats = [];
  final List<ChatsModel> archivedChats = [];
  // final List<int> chatsToDelete = [];
  final List<BotsModel> bots = [];
  BotsModel? bot;
  bool loadingBots = false;
  bool loadingchangeTitle = false;
  bool loadingdeleteAll = false;
  bool loadinggetAll = false;
  bool refresh = false;
  Timer? timer;
  String search = '';

  Future<void> getChats({final bool archived = false}) async {
    appState = AppState.busy;
    loadinggetAll = true;
    update();
    final service = RequestService(
      archived ? RequestHelper.aiArchived() : RequestHelper.aiChats(),
    );
    await service.httpGet();
    if (service.isSuccess) {
      (archived ? archivedChats : chats).clear();
      final messages = service.result['chats'];
      for (var i = 0; i < messages.length; i++) {
        (archived ? archivedChats : chats)
            .add(ChatsModel.fromJson(messages[i]));
      }
      appState = AppState.idle;
      loadinggetAll = false;

      update();
      return;
    }
    appState = AppState.failed;
    loadinggetAll = false;
    update();
  }

  Future<void> getSearchChats(
      {required final String q, final bool archived = false}) async {
    appState = AppState.busy;
    update();
    final service = RequestService(
      archived
          ? RequestHelper.aiSearchArchived(q)
          : RequestHelper.aiSearchChats(q),
    );
    await service.httpGet();
    if (service.isSuccess) {
      archivedChats.clear();
      final ch = service.result['chats'];
      for (var i = 0; i < ch.length; i++) {
        archivedChats.add(ChatsModel.fromJson(ch[i]));
      }
      appState = AppState.idle;
      update();

      return;
    }
    appState = AppState.failed;
    update();
  }

  Future<void> getBots() async {
    appState = AppState.busy;
    loadingBots = true;
    update();
    final service = RequestService(
      RequestHelper.aiBots(),
    );
    await service.httpGet();
    if (service.isSuccess) {
      bots.clear();
      final messages = service.result['bots'];
      for (var i = 0; i < messages.length; i++) {
        bots.add(BotsModel.fromJson(messages[i]));
      }
      bot = bots.first;
      appState = AppState.idle;
      loadingBots = false;
      update();
      getChats();

      return;
    }
    appState = AppState.failed;
    loadingBots = false;
    update();
  }

  Future<void> getSearchBots(String q) async {
    appState = AppState.busy;

    loadingBots = true;
    final service = RequestService(
      RequestHelper.aiSearchBots(q),
    );
    await service.httpGet();
    if (service.isSuccess) {
      bots.clear();
      final messages = service.result['bots'];
      for (var i = 0; i < messages.length; i++) {
        bots.add(BotsModel.fromJson(messages[i]));
      }
      appState = AppState.idle;
      loadingBots = false;
      update();

      return;
    }
    appState = AppState.failed;
    loadingBots = false;
    update();
  }

  // Future<void> addChatToDelete() async {
  //   final service = RequestService(RequestHelper.aiDeleteChats(),
  //       body: {"ids": chatsToDelete});
  //   await service.delete();
  //   if (service.isSuccess) {
  //     final List<ChatsModel> cs = [];
  //     for (var chat in chats) {
  //       if (!chatsToDelete.contains(chat.id)) {
  //         cs.add(chat);
  //       }
  //     }
  //     chatsToDelete.clear();
  //     chats.clear();
  //     chats.addAll(cs);

  //     appState = AppState.idle;
  //     update();

  //     return;
  //   }
  //   appState = AppState.failed;
  //   await ActionSheetUtils.showAlert(AlertData(
  //       message: 'خطا در برقراری ارتباط', aLertType: ALertType.error));

  //   update();
  // }

  Future<void> changeNameChat(int id, int index, String title,
      {final bool refresh = true}) async {
    loadingchangeTitle = true;
    update();
    final service =
        RequestService(RequestHelper.aiChangeChats(id), body: {"title": title});
    await service.put();
    if (service.isSuccess) {
      chats[index].title = title;

      appState = AppState.idle;
      loadingchangeTitle = false;
      update();
      this.refresh = refresh;
      return;
    }
    appState = AppState.failed;
    await ActionSheetUtils(navigatorKey.currentContext!).showAlert(AlertData(
        message: 'خطا در برقراری ارتباط', aLertType: ALertType.error));
    loadingchangeTitle = false;

    update();
  }

  Future<void> deleteChat(int id, int index,
      {final bool refresh = true, final bool archived = false}) async {
    final service = RequestService(RequestHelper.deleteChat(id));
    await service.delete();
    if (service.isSuccess) {
      (archived ? archivedChats : chats).removeAt(index);

      appState = AppState.idle;
      loadingchangeTitle = false;

      update();
      this.refresh = refresh;

      return;
    }
    appState = AppState.failed;
    await ActionSheetUtils(navigatorKey.currentContext!).showAlert(AlertData(
        message: 'خطا در برقراری ارتباط', aLertType: ALertType.error));
    loadingchangeTitle = false;

    update();
  }

  Future<void> deleteAllChat({final bool refresh = true}) async {
    loadingdeleteAll = true;
    update();
    final service = RequestService(
      RequestHelper.deleteAllChats(),
    );
    await service.delete();
    if (service.isSuccess) {
      chats.clear();

      appState = AppState.idle;
      loadingdeleteAll = false;

      update();
      this.refresh = refresh;

      return;
    }
    appState = AppState.failed;
    await ActionSheetUtils(navigatorKey.currentContext!).showAlert(AlertData(
        message: 'خطا در برقراری ارتباط', aLertType: ALertType.error));
    loadingdeleteAll = false;

    update();
  }

  Future<bool> archivedChat(int id, int index,
      {final bool refresh = true, final bool archived = false}) async {
    update();
    final service = RequestService(
      RequestHelper.archivedChat(id),
    );
    await service.put();
    if (service.isSuccess) {
      (archived ? archivedChats : chats).removeAt(index);

      appState = AppState.idle;

      update();
      this.refresh = refresh;

      return true;
    }
    appState = AppState.failed;
    await ActionSheetUtils(navigatorKey.currentContext!).showAlert(AlertData(
        message: 'خطا در برقراری ارتباط', aLertType: ALertType.error));

    update();
    return false;
  }
}
