import 'dart:convert';
import 'dart:developer';

import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:voice_buddies/app/models/common_model.dart';
import 'package:voice_buddies/app/models/login_model.dart';
import 'package:voice_buddies/app/models/message_model.dart';
import 'package:voice_buddies/app/utils/all_imports.dart';
import 'package:voice_buddies/app/widget/base_controller.dart';

class HomeController extends BaseController {
  List<CommonModel> msgList = [];
  LoginData? flagNotifies;
  MessageModel? messageModel;
  List<MessageData> messageList = <MessageData>[].obs;
  RefreshController refreshController = RefreshController(initialRefresh: false);

  RxBool isWarningClose = false.obs;
  @override
  Future<void> onInit() async {
    await getUserData();

    getMessageList();
    getAdminNotificationApi();
    super.onInit();
  }

  getMessageList() async {
    if (Constants.socket!.connected) {
      printAction("call thay che ");
      Constants.socket!.emit(Constants.getChatUserList, loginData!.userId);
      Constants.socket!.on(
        Constants.setChatUserList,
        (data) async {
          if (data == null) {
            printAction("Data --not recaived");
            return;
          } else {
            log("Data ---123--- setMessageList ----->>> ${json.encode(data)}");
            messageModel = MessageModel.fromJson(data);
            messageList = messageModel!.resData!;
          }
          update();
        },
      );
      printAction("call thay che 2");

      Constants.socket!.on(Constants.updateChatList, (data) {
        if (data == null) {
          return null;
        }
        printAction("Data ----- updateChatList ---->${json.encode(data)}");

        String userId = data['resData']['user_id'];
        printAction("userId  =-=-=-=-=-=-=-=-=-=-=-=->>==${messageList.length}");
        bool isExist = false;
        for (int i = 0; i < messageList.length; i++) {
          if (messageList[i].userId == userId) {
            isExist = true;
            messageList[i] = MessageData.fromJson(data['resData']);
            printAction("userId  =-=-=-=-=-=-=-=-=-=-=-=->>${messageList[i].msgId}");
            Future.delayed(const Duration(milliseconds: 1000), () {
              messageList.sort((a, b) => b.createdAt!.compareTo(a.createdAt!));
              update();
            });
            break;
          }
        }
        if (isExist == false) {
          messageList.insert(0, MessageData.fromJson(data['resData']));
          printAction("userId  =-=-=-=-=-=-=-=-=-=-=-=->>");
          isExist = true;
        }
        update();
      });
    } else {
      printAction("else else ");
    }
  }

  /// readAdminNotificationApi
  readAdminNotificationApi({notificationId, index}) async {
    FormData formData = FormData.fromMap({
      "user_id": loginData?.userId,
      "mf_id": notificationId,
    });

    final data = await APIFunction().apiCall(
      apiName: Constants.readAdminNotification,
      params: formData,
      token: loginData?.token,
    );

    LoginDataModel model = LoginDataModel.fromJson(data);

    if (model.responseCode == 1) {
      flagNotifies!.flagNotifies?.removeAt(index);
      update();
    } else {
      utils.showSnackBar(message: model.responseMsg!, statusCode: model.responseCode);
    }
  }

  /// getAdminNotificationApi
  getAdminNotificationApi() async {
    FormData formData = FormData.fromMap({
      "user_id": loginData?.userId,
    });

    final data = await APIFunction().apiCall(
      apiName: Constants.getAdminNotification,
      params: formData,
      token: loginData?.token,
    );

    LoginDataModel model = LoginDataModel.fromJson(data);

    if (model.responseCode == 1) {
      flagNotifies = model.data;
      update();
    } else {
      utils.showSnackBar(message: model.responseMsg!, statusCode: model.responseCode);
    }
  }
}
