import 'dart:convert';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/cupertino.dart';

import 'package:http/http.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/generated/locale_keys.g.dart';
import 'package:mc_common_app/models/m_response.dart';
import 'package:mc_common_app/models/user/basic_otp.dart';
import 'package:mc_common_app/models/user/change_email.dart';
import 'package:mc_common_app/models/user/change_mobile.dart';
import 'package:mc_common_app/models/user/confirm_email.dart';
import 'package:mc_common_app/models/user/confirm_mobile.dart';
import 'package:mc_common_app/models/user/confirm_password.dart';
import 'package:mc_common_app/models/user/country.dart';
import 'package:mc_common_app/models/user/forget_password_otp_compare.dart';
import 'package:mc_common_app/models/user/forget_password_otp_request.dart';
import 'package:mc_common_app/models/user/login_password.dart';
import 'package:mc_common_app/models/user/register_user.dart';
import 'package:mc_common_app/models/user/user.dart';
import 'package:mc_common_app/models/user/verify_email.dart';
import 'package:mc_common_app/repositories/user_repo.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/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';

class UserVM extends BaseVM {
  final UserRepo userRepo;

  UserVM({required this.userRepo});

  bool completeProfilePageCheckbox = false;

  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) => false);
                },
              ),
            );
          } 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) => false);
                },
              ),
            );
          } 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);
      MResponse 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) => false);
      } 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,
  }) async {
    if (Utils.passwordValidateStructure(password)) {
      if (password == confirmPassword) {
        Utils.showLoading(context);
        RegisterUserRespModel user = await userRepo.basicComplete(userId ?? "", firstName, lastName, email, password);
        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('Your password is too short');
    } else if (password.length < 8) {
      updateStrengthThreshold(2 / 4);
      updateStrengthText('Your password is acceptable but not strong');
    } else {
      if (!letterReg.hasMatch(password) || !numReg.hasMatch(password)) {
        updateStrengthThreshold(3 / 4);
        updateStrengthText('Your password is strong');
      } else {
        updateStrengthThreshold(1);
        updateStrengthText('Your password is very strong');
      }
    }
    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);
          MResponse 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}) 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);
          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) {
                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("Sorry, Only Customer's can log in this app");
              }
            }
          } 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);
          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, required String countryCode, required String phoneNum, required String password}) async {
    Utils.showLoading(context);
    Response response = await userRepo.loginV1(type == ClassType.NUMBER ? countryCode + phoneNum : phoneNum, password);
    Utils.hideLoading(context);
    LoginPasswordRespModel user = LoginPasswordRespModel.fromJson(jsonDecode(response.body));
    if (user.messageStatus == 1) {
      SharedPrefManager.setPhoneOrEmail(type == ClassType.NUMBER ? countryCode + 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}) async {
    Utils.showLoading(context);
    BasicOtpRespModel basicOtp = await userRepo.basicOtp(countryCode + phoneNum, roleId: role);
    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(countryCode + phoneNum, code, basicOtp.data!.userToken ?? "");
          Utils.hideLoading(context);
          if (user.messageStatus == 1) {
            Utils.showToast(user.message ?? "");
            navigateReplaceWithName(context, AppRoutes.completeProfile, arguments: user);
          } else {
            Utils.showToast(user.message ?? "");
          }
        },
      ));
    } else {
      Utils.showToast(basicOtp.message ?? "");
    }
  }
}
