import 'dart:convert';
import 'dart:developer';
import 'dart:io';
import 'package:easy_localization/easy_localization.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:http/src/response.dart';
import 'package:local_auth/local_auth.dart';
import 'package:mc_common_app/classes/app_state.dart';
import 'package:mc_common_app/classes/consts.dart';
import 'package:mc_common_app/config/routes.dart';
import 'package:mc_common_app/extensions/string_extensions.dart';
import 'package:mc_common_app/generated/locale_keys.g.dart';
import 'package:mc_common_app/main.dart';
import 'package:mc_common_app/models/general_models/generic_resp_model.dart';
import 'package:mc_common_app/models/general_models/generic_resp_model.dart';
import 'package:mc_common_app/models/subscriptions_models/subscription_model.dart';
import 'package:mc_common_app/models/user_models/basic_otp.dart';
import 'package:mc_common_app/models/user_models/change_email.dart';
import 'package:mc_common_app/models/user_models/change_mobile.dart';
import 'package:mc_common_app/models/user_models/confirm_email.dart';
import 'package:mc_common_app/models/user_models/confirm_mobile.dart';
import 'package:mc_common_app/models/user_models/confirm_password.dart';
import 'package:mc_common_app/models/user_models/country.dart';
import 'package:mc_common_app/models/user_models/forget_password_otp_compare.dart';
import 'package:mc_common_app/models/user_models/forget_password_otp_request.dart';
import 'package:mc_common_app/models/user_models/login_password.dart';
import 'package:mc_common_app/models/user_models/register_user.dart';
import 'package:mc_common_app/models/user_models/user.dart';
import 'package:mc_common_app/models/user_models/verify_email.dart';
import 'package:mc_common_app/repositories/user_repo.dart';
import 'package:mc_common_app/services/common_auth_service.dart';
import 'package:mc_common_app/services/common_services.dart';
import 'package:mc_common_app/utils/enums.dart';
import 'package:mc_common_app/utils/navigator.dart';
import 'package:mc_common_app/utils/shared_prefrence.dart';
import 'package:mc_common_app/utils/utils.dart';
import 'package:mc_common_app/view_models/base_view_model.dart';
import 'package:mc_common_app/view_models/chat_view_model.dart';
import 'package:mc_common_app/view_models/service_view_model.dart';
import 'package:mc_common_app/view_models/subscriptions_view_model.dart';
import 'package:mc_common_app/views/location_views/map_selection_widget.dart';
import 'package:mc_common_app/widgets/dialog/dialogs.dart';
import 'package:mc_common_app/widgets/dialog/message_dialog.dart';
import 'package:mc_common_app/widgets/dialog/otp_dialog.dart';
import 'package:mc_common_app/widgets/tab/login_email_tab.dart';
import 'package:provider/provider.dart';

class UserVM extends BaseVM {
  final UserRepo userRepo;
  final CommonAppServices commanServices;

  UserVM({required this.userRepo, required this.commanServices});

  bool completeProfilePageCheckbox = false;

  bool _loginOtherAccount = false;

  bool get loginOtherAccount => _loginOtherAccount;

  set loginOtherAccount(bool value) {
    _loginOtherAccount = value;
  }

  void updateCompleteProfilePageCheckbox(bool newValue) {
    completeProfilePageCheckbox = newValue;
    notifyListeners();
  }

  String displayStrengthText = '';

  void updateStrengthText(String newValue) {
    displayStrengthText = newValue;
    notifyListeners();
  }

  double strengthThreshold = 0.0;

  void updateStrengthThreshold(double newValue) {
    strengthThreshold = newValue;
    notifyListeners();
  }

  Future<void> changeUserEmail(BuildContext context, String email, String password) async {
    Utils.showLoading(context);
    ChanEmailRespModel otpRequest = await userRepo.changeEmailOTPRequest(email, password);
    Utils.hideLoading(context);
    if (otpRequest.messageStatus == 1) {
      showMDialog(context, child: OtpDialog(
        onClick: (String code) async {
          pop(context);
          Utils.showLoading(context);
          ConfirmEmailRespModel otpCompare = await userRepo.changeEmail(otpRequest.data!.userToken ?? "", code);
          Utils.hideLoading(context);
          if (otpCompare.messageStatus == 1) {
            showMDialog(
              context,
              child: MessageDialog(
                title: LocaleKeys.emailChangedSuccessfully.tr(),
                //"Email is Changed Successfully",
                onClick: () {
                  Navigator.of(context).pushNamedAndRemoveUntil(AppRoutes.loginWithPassword, (Route<dynamic> route) => true);
                },
              ),
            );
          } else {
            Utils.showToast(otpCompare.message ?? "");
          }
        },
      ));
    } else {
      Utils.showToast(otpRequest.message ?? "");
    }
  }

  Future<void> changeUserMobile(BuildContext context, int countryId, String mobileNo, String password) async {
    Utils.showLoading(context);
    ChangeMobileRespModel otpRequest = await userRepo.changeMobileNoOTPRequest(countryId, mobileNo, password);
    Utils.hideLoading(context);
    if (otpRequest.messageStatus == 1) {
      showMDialog(context, child: OtpDialog(
        onClick: (String code) async {
          pop(context);
          Utils.showLoading(context);
          ConfirmMobileRespModel otpCompare = await userRepo.changeMobileNo(otpRequest.data!.userToken ?? "", code);
          Utils.hideLoading(context);
          if (otpCompare.messageStatus == 1) {
            showMDialog(
              context,
              child: MessageDialog(
                title: LocaleKeys.phoneNumberVerified.tr(),
                //"Phone Number Verified",
                onClick: () {
                  Navigator.of(context).pushNamedAndRemoveUntil(AppRoutes.loginWithPassword, (Route<dynamic> route) => true);
                },
              ),
            );
          } else {
            Utils.showToast(otpCompare.message ?? "");
          }
        },
      ));
    } else {
      Utils.showToast(otpRequest.message ?? "");
    }
  }

  Future<void> changeUserPassword(BuildContext context, String newPassword, String currentPassword) async {
    if (Utils.passwordValidateStructure(newPassword)) {
      Utils.showLoading(context);
      GenericRespModel res = await userRepo.changePassword(currentPassword, newPassword);
      Utils.hideLoading(context);
      if (res.messageStatus == 1) {
        Utils.showToast(LocaleKeys.passwordIsUpdated.tr());
        //("Password is Updated");
        // navigateWithName(context, AppRoutes.loginWithPassword);
        Navigator.of(context).pushNamedAndRemoveUntil(AppRoutes.loginWithPassword, (Route<dynamic> route) => true);
      } else {
        Utils.showToast(res.message ?? "");
      }
    } else {
      Utils.showToast(LocaleKeys.passwordShouldContains.tr());
      //("Password Should contains Character, Number, Capital and small letters");
    }
  }

  Future<void> performCompleteProfile(
    BuildContext context, {
    required String password,
    required String confirmPassword,
    required String firstName,
    required String lastName,
    required String email,
    required String? userId,
    bool isNeedToPassToken = false,
  }) async {
    if (Utils.passwordValidateStructure(password)) {
      if (password == confirmPassword) {
        Utils.showLoading(context);
        RegisterUserRespModel user = await userRepo.basicComplete(
          userId ?? "",
          firstName,
          lastName,
          email,
          password,
          isNeedToPassToken: isNeedToPassToken,
        );
        Utils.hideLoading(context);
        if (user.messageStatus == 1) {
          Utils.showToast(LocaleKeys.successfullyRegistered.tr());
          pop(context);
        } else {
          Utils.showToast(user.message ?? "");
        }
      } else {
        Utils.showToast(LocaleKeys.pleaseEnterSamePassword.tr());
        //("Please enter same password");
      }
    } else {
      Utils.showToast(LocaleKeys.passwordShouldContains.tr());
      //("Password Should contains Character, Number, Capital and small letters");
    }
  }

  bool dataValidation({
    required String password,
    required String? firstName,
    required String? lastName,
    required String? email,
  }) {
    bool isValid = true;
    if (firstName!.isEmpty) {
      Utils.showToast(LocaleKeys.firstNameMandatory.tr());
      //("First name is mandatory");
      isValid = false;
    } else if (lastName!.isEmpty) {
      Utils.showToast(LocaleKeys.surnameNameMandatory.tr());
      //("Surname is mandatory");
      isValid = false;
    } else if (email!.isNotEmpty) {
      if (!Utils.isEmailValid(email)) {
        Utils.showToast(LocaleKeys.enterValidEmail.tr());
        isValid = false;
      }
    } else if (password.isEmpty) {
      Utils.showToast(LocaleKeys.passwordNameMandatory.tr());
      //("Password is mandatory");
      isValid = false;
    } else if (!completeProfilePageCheckbox) {
      Utils.showToast(LocaleKeys.pleaseAcceptTerms.tr());
      //("Please accept terms");
      isValid = false;
    }
    return isValid;
  }

  void checkPassword(String password) {
    if (password.length <= 6) {
      updateStrengthThreshold(1 / 4);
      updateStrengthText(LocaleKeys.passwordTooShort.tr());
    } else if (password.length < 8) {
      updateStrengthThreshold(2 / 4);
      updateStrengthText(LocaleKeys.passwordAcceptableStrong.tr());
    } else {
      if (!letterReg.hasMatch(password) || !numReg.hasMatch(password)) {
        updateStrengthThreshold(3 / 4);
        updateStrengthText(LocaleKeys.passwordIsStrong.tr());
      } else {
        updateStrengthThreshold(1);
        updateStrengthText(LocaleKeys.passwordVeryStrong.tr());
      }
    }
    notifyListeners();
  }

  Future<void> confirmPasswordOTP(BuildContext context, {required String userToken, required String newPassword}) async {
    if (Utils.passwordValidateStructure(newPassword)) {
      Utils.showLoading(context);
      ConfirmPasswordRespModel data = await userRepo.forgetPassword(userToken, newPassword);
      Utils.hideLoading(context);
      if (data.messageStatus == 1) {
        Utils.showToast(LocaleKeys.passwordIsUpdated.tr());
        navigateWithName(context, AppRoutes.loginWithPassword);
      } else {
        Utils.showToast(data.message ?? "");
      }
    } else {
      Utils.showToast(LocaleKeys.passwordShouldContains.tr());
    }
  }

  Future<void> verifyEmail(BuildContext context, {required String email, required String userID}) async {
    Utils.showLoading(context);
    VerifyEmailRespModel otpRequest = await userRepo.emailVerify(email, userID);
    Utils.hideLoading(context);
    if (otpRequest.messageStatus == 1) {
      showMDialog(context, child: OtpDialog(
        onClick: (String code) async {
          pop(context);
          Utils.showLoading(context);
          GenericRespModel otpCompare = await userRepo.emailVerifyOTPVerify(otpRequest.data!.userToken ?? "", code);
          Utils.hideLoading(context);
          if (otpCompare.messageStatus == 1) {
            AppState().getUser.data!.userInfo!.isEmailVerified = true;
            Utils.showToast(LocaleKeys.emailVerified.tr());
          } else {
            Utils.showToast(otpCompare.message ?? "");
          }
        },
      ));
    } else {
      Utils.showToast(otpRequest.message ?? "");
    }
    notifyListeners();
  }

  Future<void> forgetPasswordOTPMethod(BuildContext context, {required String userToken}) async {
    showMDialog(context, child: OtpDialog(
      onClick: (String code) async {
        pop(context);
        Utils.showLoading(context);
        PasswordOTPCompareResModel otpCompare = await userRepo.forgetPasswordOTPCompare(userToken, code);
        Utils.hideLoading(context);
        if (otpCompare.messageStatus == 1) {
          var userToken = otpCompare.data!.userToken;
          navigateWithName(context, AppRoutes.confirmNewPasswordPage, arguments: userToken);
        } else {
          Utils.showToast(otpCompare.message ?? "");
        }
      },
    ));
  }

  Future<void> forgetPasswordPhoneOTP(BuildContext context, {required String countryCode, required String userName, required int otpType}) async {
    Utils.showLoading(context);
    Response response = await userRepo.forgetPasswordOTPRequest(countryCode + userName, otpType);
    Utils.hideLoading(context);
    PasswordOTPRequestRespModel otpRequest = PasswordOTPRequestRespModel.fromJson(jsonDecode(response.body));
    if (otpRequest.messageStatus == 1) {
      var userToken = otpRequest.data!.userToken;
      navigateReplaceWithName(context, AppRoutes.forgetPasswordMethodPage, arguments: userToken);
    } else {
      Utils.showToast(otpRequest.message ?? "");
    }
  }

  Future<void> forgetPasswordEmailOTP(BuildContext context, {required String countryCode, required String userName, required int otpType}) async {
    Utils.showLoading(context);
    Response response = await userRepo.forgetPasswordOTPRequest(userName, otpType);
    Utils.hideLoading(context);
    PasswordOTPRequestRespModel otpRequest = PasswordOTPRequestRespModel.fromJson(jsonDecode(response.body));
    if (otpRequest.messageStatus == 1) {
      Utils.showToast(LocaleKeys.codeSentToEmail.tr());
      showMDialog(context, child: OtpDialog(
        onClick: (String code) async {
          pop(context);
          Utils.showLoading(context);
          PasswordOTPCompareResModel otpCompare = await userRepo.forgetPasswordOTPCompare(otpRequest.data!.userToken ?? "", code);
          Utils.hideLoading(context);
          if (otpCompare.messageStatus == 1) {
            var userToken = otpCompare.data!.userToken;
            navigateWithName(context, AppRoutes.confirmNewPasswordPage, arguments: userToken);
          } else {
            Utils.showToast(otpCompare.message ?? "");
          }
        },
      ));
    } else {
      Utils.showToast(otpRequest.message ?? "");
    }
  }

  Future<void> performBasicOtpLoginSelectionPage(BuildContext context, {required String userToken, required AppType appType, String? loginType}) async {
    log("loginType: $loginType");
    if (loginType == "3" || loginType == "4") {
      //Utils.showLoading(context);
      LoginPasswordRespModel user = await userRepo.loginV2OTP(userToken, loginType!);
      if (user.messageStatus == 1) {
        Response response2 = await userRepo.loginV2OTPVerify(
          user.data!.userToken ?? "",
          "9999",
          AppState().getDeviceType ?? "1",
          AppState().getDeviceToken ?? "",
        );
        RegisterUserRespModel verifiedUser = RegisterUserRespModel.fromJson(jsonDecode(response2.body));
        if (verifiedUser.messageStatus == 1) {
          User user = User.fromJson(jsonDecode(response2.body));
          if (appType == AppType.provider) {
            if (user.data!.userInfo!.roleId == 5 || user.data!.userInfo!.roleId == 6 || user.data!.userInfo!.roleId == 7) {
              AppState().setUser = user;
              SharedPrefManager.setUserToken(user.data!.accessToken ?? "");
              SharedPrefManager.setUserId(user.data!.userInfo!.userId ?? "");
              SharedPrefManager.setRefreshToken(user.data!.refreshToken ?? "");
              SharedPrefManager.setData(jsonEncode(user.data!.userInfo!.toJson()));
              navigateReplaceWithName(context, AppRoutes.dashboard);
            } else {
              Utils.showToast(LocaleKeys.onlyProviderApp.tr());
            }
          } else if (user.data!.userInfo!.roleId == 4) {
            if (user.data!.userInfo!.roleId == 4) {
              AppState().setUser = user;
              SharedPrefManager.setUserToken(user.data!.accessToken ?? "");
              SharedPrefManager.setUserId(user.data!.userInfo!.userId ?? "");
              SharedPrefManager.setRefreshToken(user.data!.refreshToken ?? "");
              SharedPrefManager.setData(jsonEncode(user.data!.userInfo!.toJson()));
              navigateReplaceWithName(context, AppRoutes.dashboard);
            } else {
              Utils.showToast(LocaleKeys.onlyCustomerApp.tr());
            }
          }
        } else {
          Utils.showToast(verifiedUser.message ?? "");
        }
      }
    } else {
      // Utils.showLoading(context);
      LoginPasswordRespModel user = await userRepo.loginV2OTP(userToken, "1");
      // Utils.hideLoading(context);
      if (user.messageStatus == 1) {
        showMDialog(context, child: OtpDialog(
          onClick: (String code) async {
            pop(context);
            Utils.showLoading(context);
            Response response2 = await userRepo.loginV2OTPVerify(
              user.data!.userToken ?? "",
              code,
              AppState().getDeviceType ?? "1",
              AppState().getDeviceToken ?? "",
            );
            Utils.hideLoading(context);
            RegisterUserRespModel verifiedUser = RegisterUserRespModel.fromJson(jsonDecode(response2.body));
            if (verifiedUser.messageStatus == 1) {
              User user = User.fromJson(jsonDecode(response2.body));
              if (appType == AppType.provider) {
                if (user.data!.userInfo!.roleId == 5 || user.data!.userInfo!.roleId == 6 || user.data!.userInfo!.roleId == 7) {
                  AppState().setUser = user;
                  SharedPrefManager.setUserToken(user.data!.accessToken ?? "");
                  SharedPrefManager.setUserId(user.data!.userInfo!.userId ?? "");
                  SharedPrefManager.setRefreshToken(user.data!.refreshToken ?? "");
                  SharedPrefManager.setData(jsonEncode(user.data!.userInfo!.toJson()));
                  navigateReplaceWithName(context, AppRoutes.dashboard);
                } else {
                  Utils.showToast(LocaleKeys.onlyProviderApp.tr());
                  //("Sorry, Only Customer's can log in this app");
                }
              } else if (user.data!.userInfo!.roleId == 4) {
                if (user.data!.userInfo!.roleId == 4) {
                  AppState().setUser = user;
                  SharedPrefManager.setUserToken(user.data!.accessToken ?? "");
                  SharedPrefManager.setUserId(user.data!.userInfo!.userId ?? "");
                  SharedPrefManager.setRefreshToken(user.data!.refreshToken ?? "");
                  SharedPrefManager.setData(jsonEncode(user.data!.userInfo!.toJson()));
                  navigateReplaceWithName(context, AppRoutes.dashboard);
                } else {
                  Utils.showToast(LocaleKeys.onlyCustomerApp.tr());
                }
              } else {
                Utils.showToast("Please verify your credentials and role type.");
              }
            } else {
              Utils.showToast(verifiedUser.message ?? "");
            }
          },
        ));
      } else {
        Utils.showToast(user.message ?? "");
      }
    }
  }

  Future<String> performApiCallLoginVerificationPage(BuildContext context) async {
    String userToken = "";
    String userName = await SharedPrefManager.getPhoneOrEmail();
    String password = await SharedPrefManager.getUserPassword();
    if (userName.isNotEmpty && userName.isNotEmpty) {
      Utils.showLoading(context);
      Response response = await userRepo.loginV1(userName, password);
      Utils.hideLoading(context);
      LoginPasswordRespModel user = LoginPasswordRespModel.fromJson(jsonDecode(response.body));
      if (user.messageStatus == 1) {
        userToken = user.data!.userToken ?? "";
        // navigateWithName(context, AppRoutes.loginMethodSelection, arguments: user.data!.userToken);
      } else {
        Utils.showToast(user.message ?? "");
      }
    }
    return userToken;
  }

  Future<void> performBasicOtpLoginVerificationPage(BuildContext context, {required String userToken}) async {
    Utils.showLoading(context);
    LoginPasswordRespModel user = await userRepo.loginV2OTP(userToken, "1");
    Utils.hideLoading(context);
    if (user.messageStatus == 1) {
      showMDialog(context, child: OtpDialog(
        onClick: (String code) async {
          pop(context);
          Utils.showLoading(context);
          Response response2 = await userRepo.loginV2OTPVerify(
            user.data!.userToken ?? "",
            code,
            AppState().getDeviceType ?? "1",
            AppState().getDeviceToken ?? "",
          );
          Utils.hideLoading(context);
          RegisterUserRespModel verifiedUser = RegisterUserRespModel.fromJson(jsonDecode(response2.body));
          if (verifiedUser.messageStatus == 1) {
            User user = User.fromJson(jsonDecode(response2.body));
            AppState().setUser = user;
            navigateReplaceWithName(context, AppRoutes.dashboard);
          } else {
            Utils.showToast(verifiedUser.message ?? "");
          }
        },
      ));
    } else {
      Utils.showToast(user.message ?? "");
    }
  }

  Future<void> performBasicOtpLoginVerifyAccountPage(BuildContext context, {required String phoneNum, required int otpType}) async {
    Utils.showLoading(context);
    BasicOtpRespModel basicOtp = await userRepo.basicOtp(phoneNum, otpType: otpType);
    Utils.hideLoading(context);
    if (basicOtp.messageStatus == 1) {
      showMDialog(context, child: OtpDialog(
        onClick: (String code) async {
          pop(context);
          Utils.showLoading(context);
          RegisterUserRespModel user = await userRepo.basicVerify(phoneNum, code, basicOtp.data!.userToken ?? "");
          Utils.hideLoading(context);
          if (user.messageStatus == 1) {
            Utils.showToast(user.message ?? "");
            showMDialog(
              context,
              child: MessageDialog(
                title: LocaleKeys.phoneNumberVerified.tr(),
                //"Phone Number Verified",
                onClick: () {
                  pop(context);
                  navigateWithName(context, AppRoutes.profile1, arguments: user);
                },
              ),
            );
          } else {
            Utils.showToast(user.message ?? "");
          }
        },
      ));
    } else {
      Utils.showToast(basicOtp.message ?? "");
    }
  }

  Future<void> performBasicOtpLoginWithPasswordPage(BuildContext context, {required ClassType type, String? countryCode, required String phoneNum, required String password}) async {
    Utils.showLoading(context);
    Response response = await userRepo.loginV1(
        type == ClassType.NUMBER && countryCode != null
            ? countryCode + phoneNum
            : type == ClassType.NUMBER && countryCode == null
                ? phoneNum
                : phoneNum,
        password);
    Utils.hideLoading(context);
    LoginPasswordRespModel user = LoginPasswordRespModel.fromJson(jsonDecode(response.body));
    if (user.messageStatus == 1) {
      SharedPrefManager.setPhoneOrEmail(type == ClassType.NUMBER && countryCode != null
          ? countryCode + phoneNum
          : type == ClassType.NUMBER && countryCode == null
              ? phoneNum
              : phoneNum);
      SharedPrefManager.setUserPassword(password);
      navigateReplaceWithName(context, AppRoutes.loginMethodSelection, arguments: user.data!.userToken);
    } else {
      Utils.showToast(user.message ?? "");
    }
  }

  Future<Country> getAllCountries() async {
    return await userRepo.getAllCountries();
  }

  Future<void> performBasicOtpRegisterPage(BuildContext context,
      {required String countryCode, required String phoneNum, required int role, bool isNeedToPassToken = false, VoidCallback? reloadPage}) async {
    Utils.showLoading(context);
    BasicOtpRespModel basicOtp = await userRepo.basicOtp(countryCode + phoneNum, roleId: role, isNeedToPassToken: isNeedToPassToken);
    Utils.hideLoading(context);
    if (basicOtp.messageStatus == 1) {
      showMDialog(context, child: OtpDialog(
        onClick: (String code) async {
          if (reloadPage == null) pop(context);
          Utils.showLoading(context);
          RegisterUserRespModel user = await userRepo.basicVerify(
            countryCode + phoneNum,
            code,
            basicOtp.data!.userToken ?? "",
            isNeedToPassToken: isNeedToPassToken,
          );
          Utils.hideLoading(context);
          if (user.messageStatus == 1) {
            Utils.showToast(user.message ?? "");
            user.data!.roleId = role;
            user.data!.isNeedToPassToken = isNeedToPassToken;
            navigateReplaceWithName(context, AppRoutes.completeProfile, arguments: user).then((value) {
              if (reloadPage != null) {
                reloadPage();
              }
            });
          } else {
            Utils.showToast(user.message ?? "");
          }
        },
      ));
    } else {
      Utils.showToast(basicOtp.message ?? "");
    }
  }

  // Aamir Code
  List<BiometricType>? availBio;

  Future<void> verifiyAuth({
    BuildContext? context,
    String? userToken,
    AppType? apptype,
    String? loginType,
  }) async {
    bool auth = await CommonAuthImp().authenticate();
    if (auth) {
      performBasicOtpLoginSelectionPage(context!, userToken: userToken!, appType: apptype!, loginType: loginType);
    }
  }

  Future<void> getAvailBio() async {
    availBio = await CommonAuthImp().getAvailBio();
  }

  bool isBioAvailable(BiometricType bioType) {
    if (availBio == null) return true;
    if (availBio!.contains(bioType)) {
      return false;
    } else {
      return true;
    }
  }

  Future<void> updateUserImage(BuildContext context) async {
    File? myPick = await commanServices.pickFile(context, fileType: FileType.image);
    if (myPick != null) {
      userRepo.updateUserImage(encodeBase64Image(myPick)).whenComplete(() {
        AppState().getUser.data!.userInfo!.userLocalImage = myPick;
      });
    }
    notifyListeners();
  }

  String encodeBase64Image(File file) {
    List<int> imageBytes = file.readAsBytesSync();
    print(imageBytes);
    return base64Encode(imageBytes);
  }

  Future<void> isAlreadyUserLoggedin(BuildContext context) async {
    String uName = await SharedPrefManager.getPhoneOrEmail();
    String pass = await SharedPrefManager.getUserPassword();
    if (!loginOtherAccount && uName.isNotEmpty && pass.isNotEmpty) {
      getAvailBio();
      if (uName.isNum()) {
        performBasicOtpLoginWithPasswordPage(context, type: ClassType.NUMBER, countryCode: null, phoneNum: uName, password: pass);
      }
      if (uName.isValidEmail()) {
        performBasicOtpLoginWithPasswordPage(context, type: ClassType.EMAIL, countryCode: null, phoneNum: uName, password: pass);
      }
      logger.d("Skip Login Triggered");
    }
  }

  void otherLogin(BuildContext context) {
    _loginOtherAccount = true;
    navigateReplaceWithName(context, AppRoutes.registerSelection);
    // navigateReplaceWithName(context, AppRoutes.loginWithPassword);
  }

  void changeLanguage(BuildContext context) {
    print("${EasyLocalization.of(context)?.currentLocale}");
    if (EasyLocalization.of(context)?.currentLocale?.countryCode == "SA") {
      context.setLocale(const Locale("en", "US"));
    } else {
      context.setLocale(const Locale('ar', 'SA'));
    }
    // notifyListeners();
  }

  void logout(BuildContext context) async {
    Response value = await userRepo.logoutUser();
    if (value.body.isNotEmpty) {
      print(value.body);
      print("Logout");
    }

    SharedPrefManager.setPhoneOrEmail("");
    SharedPrefManager.setUserPassword("");
    context.read<ChatVM>().closeHubConnection();
    if (AppState().getUser.data!.userInfo!.userLocalImage != null) {
      AppState().getUser.data!.userInfo!.userLocalImage = null;
      AppState().getUser.data!.userInfo!.userImageUrl = null;
    }
    AppState().setUser = null;
    if (AppState().currentAppType == AppType.provider) {
      AppState().setproviderSubscription = null;
      context.read<SubscriptionsVM>().mySubscriptionsBySp.clear();
      context.read<SubscriptionsVM>().allSubscriptions = SubscriptionModel();
    }

    navigateReplaceWithNameUntilRoute(context, AppRoutes.registerSelection);
  }
}
