import 'package:didvan/main.dart';
import 'package:didvan/models/ai/bot_assistants_model.dart';
import 'package:didvan/models/ai/bot_assistants_req_model.dart';
import 'package:didvan/models/ai/bots_model.dart';
import 'package:didvan/models/ai/file_create_assistants_model.dart';
import 'package:didvan/models/ai/tools_model.dart';
import 'package:didvan/models/enums.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/views/ai/history_ai_chat_state.dart';
import 'package:flutter/cupertino.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';

class CreateBotAssistantsState extends CoreProvier {
  List<BotsModel> imageBots = [];
  bool loadingImageBots = false;
  bool loadingCreate = false;
  bool loadingName = false;
  bool successName = false;
  bool loading = false;
  BotAssistants? assistant;
  String name = '';
  String prompt = '';
  String desc = '';
  // String? youtubeLink;
  late List<BotsModel> allBots =
      navigatorKey.currentContext!.read<HistoryAiChatState>().bots;

  final List<String> botModels = ['مدل زبانی', 'مدل تصویری'];
  late BotsModel? initialBot = allBots.first;

  List<String> countOfLink = [''];
  List<FileCreateAssistantsModel> files = [];
  ValueNotifier<XFile?> image = ValueNotifier(null);
  String selectedBotType = 'text';
  bool isPrivate = true;

  Future getImageToolsBots() async {
    loadingImageBots = true;

    final service = RequestService(
      RequestHelper.tools(),
    );
    await service.httpGet();
    if (service.isSuccess) {
      final ToolsModel toolsModel = ToolsModel.fromJson(service.result);
      if (toolsModel.tools != null) {
        imageBots = toolsModel.tools!.first.bots ?? [];
      } else {
        imageBots = [];
      }

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

  Future<String?> createAssistants(
      {required final BotAssistantsReqModel data, final int? id}) async {
    loadingCreate = true;
    update();

    final service = RequestService(
        (id != null
            ? RequestHelper.updateAssistants(id)
            : RequestHelper.createAssistants()),
        body: data.toJson());
    await service.multipartFilesCreateAssismants(
        files: data.files,
        image: data.image,
        method: id != null ? 'PUT' : 'POST');
    if (service.isSuccess) {
      appState = AppState.idle;
      loadingCreate = false;
      update();
      return null;
    }
    appState = AppState.failed;
    loadingCreate = false;
    update();
    return service.errorMessage;
  }

  Future getAnAssistant({required final int id}) async {
    await getImageToolsBots();

    loading = true;
    update();
    final service = RequestService(
      RequestHelper.getAssistant(id),
    );
    await service.httpGet();
    if (service.isSuccess) {
      assistant = BotAssistants.fromJson(service.result['bot']);
      if (assistant != null) {
        name = assistant!.name ?? '';
        prompt = assistant!.prompt ?? '';
        desc = assistant!.description ?? '';
        //  youtubeLink = assistant!.;
        isPrivate = assistant!.private ?? true;
        if (files.isEmpty &&
            assistant!.files != null &&
            assistant!.files!.isNotEmpty) {
          for (var file in assistant!.files!) {
            files.add(FileCreateAssistantsModel(
                fromNetwork: true, file: null, url: file));
          }
        }
        countOfLink = assistant!.websites ?? [''];

        final list = [...allBots, ...imageBots];
        for (var bot in list) {
          if (bot.id == assistant!.botId) {
            initialBot = bot;
            break;
          }
        }
        selectedBotType = initialBot?.responseType ?? 'text';
      }
      if (initialBot == null) {
        selectedBotType == 'text' ? allBots.first : imageBots.first;
      }
      appState = AppState.idle;
      loading = false;
      update();
      return;
    }
    appState = AppState.failed;
    loading = false;
    update();
  }

  Future<bool> deleteAssistants({required final int id}) async {
    loadingCreate = true;
    update();

    final service = RequestService(RequestHelper.getAssistant(id));
    await service.delete();
    if (service.isSuccess) {
      appState = AppState.idle;
      loadingCreate = false;
      update();
      return true;
    }
    appState = AppState.failed;
    loadingCreate = false;
    update();
    return false;
  }

  Future getAssistantsName({required final String name}) async {
    loadingName = true;
    update();

    final service =
        RequestService(RequestHelper.nameOfAssistant(), body: {'name': name});
    await service.post();
    if (service.isSuccess) {
      appState = AppState.idle;
      loadingName = false;
      if (service.result['available'] as bool) {
        successName = true;
      } else {
        successName = false;
      }

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

    update();
  }
}
