
import 'package:didvan/models/ai/ai_chat_args.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';

class AiState extends CoreProvier {
  int page = 0;
  Tools? tool;
  AiChatArgs? currentChatArgs;
  bool isChatting = false;

  bool loading = true;
  List<Tools>? tools;
  
  Future<void> Function()? onClearChatCallback;
  
  bool _isStartingChat = false;

  Future<void> startChat(AiChatArgs args) async {
    if (_isStartingChat) {
      return;
    }
    
    _isStartingChat = true;
    
    try {
      if (onClearChatCallback != null) {
        await onClearChatCallback!();
        await Future.delayed(const Duration(milliseconds: 50));
      }
      currentChatArgs = args;
      isChatting = true;
      notifyListeners();
    } finally {
      _isStartingChat = false;
    }
  }

  void endChat() {
    currentChatArgs = null;
    isChatting = false;
    notifyListeners();
  }

  void getTools() async {
    final service = RequestService(
      RequestHelper.tools(),
    );
    await service.httpGet();
    if (service.isSuccess) {
      final ToolsModel toolsModel = ToolsModel.fromJson(service.result);
      tools = toolsModel.tools!;
      tools ??= [];
      appState = AppState.idle;
      loading = false;
      update();
      return;
    }
    appState = AppState.failed;
    loading = false;
    update();
  }

  void goToAi() {
    page = 0;
    update();
  }

  void goToToolBox({required final Tools tool}) {
    page = 1;
    this.tool = tool;
    update();
  }
}