import 'package:diplomaticquarterapp/config/config.dart';
import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/config/size_config.dart';
import 'package:diplomaticquarterapp/core/service/AuthenticatedUserObject.dart';
import 'package:diplomaticquarterapp/core/viewModels/appointment_rate_view_model.dart';
import 'package:diplomaticquarterapp/core/viewModels/pharmacyModule/pharmacy_module_view_model.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/extensions/string_extensions.dart';
import 'package:diplomaticquarterapp/locator.dart';
import 'package:diplomaticquarterapp/models/Appointments/toDoCountProviderModel.dart';
import 'package:diplomaticquarterapp/models/Authentication/check_activation_code_response.dart';
import 'package:diplomaticquarterapp/models/Authentication/check_paitent_authentication_req.dart';
import 'package:diplomaticquarterapp/models/Authentication/select_device_imei_res.dart';
import 'package:diplomaticquarterapp/models/Authentication/send_activation_request.dart';
import 'package:diplomaticquarterapp/pages/landing/landing_page.dart';
import 'package:diplomaticquarterapp/pages/login/register_new.dart';
import 'package:diplomaticquarterapp/pages/rateAppointment/rate_appointment_doctor.dart';
import 'package:diplomaticquarterapp/routes.dart';
import 'package:diplomaticquarterapp/services/authentication/auth_provider.dart';
import 'package:diplomaticquarterapp/services/clinic_services/get_clinic_service.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/date_uitl.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/uitl/utils.dart';
import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart';
import 'package:diplomaticquarterapp/widgets/card/rounded_container.dart';
import 'package:diplomaticquarterapp/widgets/data_display/text.dart';
import 'package:diplomaticquarterapp/widgets/otp/sms-popup.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:intl/intl.dart';
import 'package:local_auth/auth_strings.dart';
import 'package:local_auth/local_auth.dart';
import 'package:provider/provider.dart';

class ConfirmLogin extends StatefulWidget {
  final Function changePageViewIndex;
  final fromRegistration;
  const ConfirmLogin({Key key, this.changePageViewIndex, this.fromRegistration = false}) : super(key: key);

  @override
  _ConfirmLogin createState() => _ConfirmLogin();
}

class _ConfirmLogin extends State<ConfirmLogin> {
  final LocalAuthentication auth = LocalAuthentication();
  var _availableBiometrics;
  var sharedPref = new AppSharedPreferences();
  bool authenticated;
  final authService = new AuthProvider();
  PharmacyModuleViewModel pharmacyModuleViewModel = locator<PharmacyModuleViewModel>();
  int mobileNumber;
  String errorMsg = '';
  SelectDeviceIMEIRES user;
  bool isLoading = false;
  var registerd_data;
  bool isMoreOption = false;
  var zipCode;

  var patientOutSA;

  var loginTokenID;

  var loginType;

  var deviceToken;

  var lastLogin;

  int selectedOption;

  bool onlySMSBox = false;
  var userData;

  static BuildContext _context;

  static bool _loading;

  int fingrePrintBefore;

  AuthenticatedUserObject authenticatedUserObject = locator<AuthenticatedUserObject>();
  AppointmentRateViewModel appointmentRateViewModel = locator<AppointmentRateViewModel>();
  ProjectViewModel projectViewModel;

  ToDoCountProviderModel toDoProvider;

  var dob;
  int isHijri;
  var healthId;

  @override
  void initState() {
    _getAvailableBiometrics();
    setDefault();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    toDoProvider = Provider.of<ToDoCountProviderModel>(context);

    return Scaffold(
      backgroundColor: Color(0xfff8f8f8),
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios),
          color: Color(0xff2B353E),
          onPressed: () => Navigator.pop(context),
        ),
      ),
      body: Padding(
        padding: EdgeInsets.only(bottom: 20, left: 21, right: 21),
        child: Column(
          children: [
            Expanded(
              child: ListView(
                padding: EdgeInsets.zero,
                physics: BouncingScrollPhysics(),
                children: [
                  SizedBox(height: 12),
                  if (user != null && isMoreOption == false)
                    Column(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          TranslationBase.of(context).welcomeBack,
                          style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Color(0xff2B353E), letterSpacing: -0.64),
                        ),
                        Text(
                          user.name.toLowerCase().capitalizeFirstofEach,
                          style: TextStyle(fontSize: 24, fontWeight: FontWeight.w700, color: Color(0xff2B353E), height: 1, letterSpacing: -1.44),
                        ),
                        SizedBox(height: 10),
                        Text(
                          TranslationBase.of(context).accountInfo,
                          style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Color(0xff2B353E), letterSpacing: -0.64, height: 25 / 16),
                        ),
                        Container(
                          height: 72,
                          margin: EdgeInsets.only(top: 23, bottom: 23),
                          alignment: Alignment.center,
                          padding: EdgeInsets.only(left: 17, right: 12),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(10),
                            color: Colors.white,
                            border: Border.all(
                              color: Color(0xffefefef),
                              width: 1,
                            ),
                          ),
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  Text(
                                    TranslationBase.of(context).lastLoginAt.toCamelCase,
                                    style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Color(0xff2B353E), letterSpacing: -0.64),
                                  ),
                                  Text(
                                    user.editedOn != null
                                        ? DateUtil.getDayMonthYearDateFormatted(DateUtil.convertStringToDate(user.editedOn))
                                        : user.createdOn != null
                                            ? DateUtil.getDayMonthYearDateFormatted(DateUtil.convertStringToDate(user.createdOn))
                                            : '--',
                                    style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Color(0xff2B353E), letterSpacing: -0.48),
                                  ),
                                ],
                              ),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  Text(
                                    TranslationBase.of(context).lastLoginWith.toCamelCase,
                                    style: TextStyle(
                                      fontSize: 10,
                                      fontWeight: FontWeight.w600,
                                      color: Color(0xff575757),
                                    ),
                                  ),
                                  Text(
                                    " " + getType(user.logInType, context),
                                    style: TextStyle(
                                      fontSize: 12,
                                      fontWeight: FontWeight.w600,
                                      color: Color(0xff2B353E),
                                    ),
                                  ),
                                  Expanded(child: SizedBox()),
                                  Text(
                                    user.editedOn != null
                                        ? DateUtil.formatDateToTimeLang(DateUtil.convertStringToDate(user.editedOn), false)
                                        : user.createdOn != null
                                            ? DateUtil.formatDateToTimeLang(DateUtil.convertStringToDate(user.createdOn), false)
                                            : '--',
                                    style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Color(0xff575757), letterSpacing: -0.48),
                                  ),
                                ],
                              )
                            ],
                          ),
                        ),
                        Text(
                          TranslationBase.of(context).pleaseVerify,
                          style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Color(0xff2E303A), letterSpacing: -0.64),
                        ),
                        GridView(
                          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, crossAxisSpacing: 13, mainAxisSpacing: 9),
                          physics: NeverScrollableScrollPhysics(),
                          padding: EdgeInsets.only(top: 9),
                          shrinkWrap: true,
                          children: [
                            getButton(3),
                            getButton(2),
                            getButton(1),
                            getButton(4),
                          ],
                        )
                      ],
                    )
                  else
                    Column(mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
                      Image.asset(
                        'assets/images/habib-logo.png',
                        height: 90,
                        width: 90,
                      ),
                      SizedBox(height: 23),
                      this.onlySMSBox == false
                          ? Text(
                              TranslationBase.of(context).verifyLoginWith,
                              style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Color(0xff2B353E), letterSpacing: -0.64, height: 25 / 16),
                            )
                          : Text(
                              TranslationBase.of(context).verifyFingerprint2,
                              style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Color(0xff2B353E), letterSpacing: -0.64, height: 25 / 16),
                            ),
                      SizedBox(height: 23),
                      Text(
                        TranslationBase.of(context).pleaseVerify,
                        style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Color(0xff2E303A), letterSpacing: -0.64),
                      ),
                      GridView(
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, crossAxisSpacing: 13, mainAxisSpacing: 9),
                        physics: NeverScrollableScrollPhysics(),
                        padding: EdgeInsets.only(top: 9),
                        shrinkWrap: true,
                        children: [
                          if (onlySMSBox == false) getButton(3),
                          if (onlySMSBox == false) getButton(2),
                          getButton(1),
                          getButton(4),
                        ],
                      ),
                    ]),
                ],
              ),
            ),
            SizedBox(
              height: 12,
            ),
            DefaultButton(
              TranslationBase.of(context).useAnotherAccount,
              () {
                projectViewModel.analytics.loginRegistration.login_with_other_account();
                Navigator.of(context).pushNamed(LOGIN_TYPE);
              },
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _getAvailableBiometrics() async {
    var availableBiometrics;
    try {
      availableBiometrics = await auth.getAvailableBiometrics();
    } on PlatformException catch (e) {
      AppToast.showErrorToast(message: e.message);
      print(e);
    }
    if (!mounted) return;

    setState(() {
      _availableBiometrics = availableBiometrics;
    });
  }

  int login_method = 0;
  authenticateUser(int type, {int isActive}) {
    GifLoaderDialogUtils.showMyDialog(context);
    if (type == 2 || type == 3) {
      fingrePrintBefore = type;
    }
    this.selectedOption = fingrePrintBefore != null ? fingrePrintBefore : type;

    login_method = type;
    switch (type) {
      case 1:
        this.loginWithSMS(type);
        break;
      case 2:
        this.loginWithFingurePrintFace(type, isActive);
        break;
      case 3:
        this.loginWithFingurePrintFace(type, isActive);
        break;
      case 4:
        this.loginWithSMS(type);
        break;
      default:
        break;
    }
    sharedPref.setInt(LAST_LOGIN, this.selectedOption); //this.cs.sharedService.setStorage(this.selectedOption, AuthenticationService.LAST_LOGIN);
  }

  loginWithSMS(type) {
    //if (!el.disabled) {
    if (this.user != null && this.registerd_data == null) {
      this.checkUserAuthentication(type);
    } else {
      if (this.loginTokenID != null) {
        // Future.delayed(Duration(seconds: 1), () {
        this.sendActivationCode(type);
        //  });
      } else {
        this.checkUserAuthentication(type);
      }
    }
  }

  checkUserAuthentication(type) {
    showLoader(true);
    var req = getCommonRequest(type: type);
    req.logInTokenID = "";

    var request = CheckPatientAuthenticationReq.fromJson(req.toJson());

    sharedPref.setObject(REGISTER_DATA_FOR_REGISTER, request);
    authService
        .checkPatientAuthentication(request)
        .then((value) => {
              GifLoaderDialogUtils.hideDialog(context),
              if (value['isSMSSent'])
                {
                  sharedPref.setString(LOGIN_TOKEN_ID, value['LogInTokenID']),
                  this.loginTokenID = value['LogInTokenID'],
                  sharedPref.setObject(REGISTER_DATA_FOR_LOGIIN, request),
                  // Future.delayed(Duration(seconds: 1), () {
                  this.sendActivationCode(type)
                  //  })
                }
              else
                {
                  if (value['IsAuthenticated']) {this.checkActivationCode()}
                }
            })
        .catchError((err) {
      print(err);
      GifLoaderDialogUtils.hideDialog(context);
    });
  }

  sendActivationCode(type) async {
    var request = this.getCommonRequest(type: type);
    request.sMSSignature = await SMSOTP.getSignature();
    GifLoaderDialogUtils.showMyDialog(context);
    if (healthId != null) {
      // final DateFormat dateFormat = DateFormat('MM/dd/yyyy');
      // final DateFormat dateFormat2 = DateFormat('dd/MM/yyyy');
      request.dob = dob; //isHijri == 1 ? dob : dateFormat2.format(dateFormat.parse(dob));
      request.healthId = healthId;
      request.isHijri = isHijri;
      await this.authService.sendActivationCodeRegister(request).then((result) {
        GifLoaderDialogUtils.hideDialog(context);
        if (result != null && result['isSMSSent'] == true) {
          this.startSMSService(type);
        }
      }).catchError((r) {
        GifLoaderDialogUtils.hideDialog(context);
      });
    } else {
      request.dob = "";
      request.healthId = "";
      request.isHijri = 0;
      await this.authService.sendActivationCode(request).then((result) {
        GifLoaderDialogUtils.hideDialog(context);
        if (result != null && result['isSMSSent'] == true) {
          this.startSMSService(type);
        }
      }).catchError((r) {
        GifLoaderDialogUtils.hideDialog(context);
      });
    }
  }

  var tempType;

  startSMSService(type) {
    tempType = type;
    new SMSOTP(
      context,
      type,
      this.mobileNumber,
      (value) {
        this.checkActivationCode(value: value);
      },
      () => {
        Navigator.pop(context),
      },
    ).displayDialog(context);
  }

  loginWithFingurePrintFace(type, int isActive) async {
    if (isActive == 1 || isActive == 0) {
      const iosStrings =
          const IOSAuthMessages(cancelButton: 'cancel', goToSettingsButton: 'settings', goToSettingsDescription: 'Please set up your Touch ID.', lockOut: 'Please reenable your Touch ID');

      try {
        authenticated = await auth.authenticateWithBiometrics(localizedReason: 'Scan your fingerprint to authenticate', useErrorDialogs: true, stickyAuth: true, iOSAuthStrings: iosStrings);
      } on PlatformException catch (e) {
        GifLoaderDialogUtils.hideDialog(context);
        AppToast.showErrorToast(message: 'Please enable your Touch or Face ID');
      }

      if (authenticated == true) {
        // if (user != null && (user.logInType == 2 || user.logInType == 3)) {
        //   this.checkActivationCode();
        // } else {

        var request = this.getCommonRequest(type: type);
        this.getMobileInfo(request);
        //}
      }
    }
  }

  getMobileInfo(request) {
    // GifLoaderDialogUtils.showMyDialog(context);
    this.authService.getLoginInfo(request).then((result) {
      GifLoaderDialogUtils.hideDialog(context);
      if (result['SMSLoginRequired'] == false) {
        this.loginTokenID = result['LogInTokenID'];
        this.patientOutSA = result['PatientOutSA'];
        // sms for register the biometric
        if (result['isSMSSent']) {
          setState(() {
            isMoreOption = true;
            this.onlySMSBox = true;
            // this.fingrePrintBefore = true;
          });
          //this.button();
        } else {
          setDefault();
          checkActivationCode();
        }
      } else {
        if (result['IsAuthenticated'] == true) {
          setState(() {
            isMoreOption = true;
            this.onlySMSBox = true;
            // this.fingrePrintBefore = true;
          });
        }
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
    });
  }

  setDefault() async {
    if (await sharedPref.getObject(IMEI_USER_DATA) != null) user = SelectDeviceIMEIRES.fromJson(await sharedPref.getObject(IMEI_USER_DATA));

    if (await sharedPref.getObject(REGISTER_DATA_FOR_LOGIIN) != null) {
      isMoreOption = true;
      this.registerd_data = CheckPatientAuthenticationReq.fromJson(await sharedPref.getObject(REGISTER_DATA_FOR_LOGIIN));
    }

    this.mobileNumber = this.registerd_data != null ? this.registerd_data.patientMobileNumber : int.parse(this.user.mobile);
    this.zipCode = this.registerd_data != null
        ? this.registerd_data.zipCode
        : this.user.outSA == true
            ? "971"
            : "966";
    this.patientOutSA = this.registerd_data != null
        ? this.registerd_data.zipCode == "966"
            ? 0
            : 1
        : this.user.outSA;
    if (this.registerd_data != null) {
      this.loginTokenID = await sharedPref.getString(LOGIN_TOKEN_ID);
      this.loginType = this.registerd_data.searchType;
    }
    var nhic = await sharedPref.getObject(NHIC_DATA);
    if (nhic != null) {
      final DateFormat dateFormat = DateFormat('MM/dd/yyyy');
      final DateFormat dateFormat2 = DateFormat('dd/MM/yyyy');
      dob = nhic['IsHijri'] ? nhic['DateOfBirth'] : dateFormat2.format(dateFormat.parse(nhic['DateOfBirth']));

      isHijri = nhic['IsHijri'] ? 1 : 0;
      healthId = nhic['HealthId'];
    }
    this.deviceToken = await sharedPref.getString(PUSH_TOKEN);
    this.lastLogin = await sharedPref.getInt(LAST_LOGIN) != null
        ? await sharedPref.getInt(LAST_LOGIN)
        : user != null
            ? user.logInType
            : null;

    //this.cs.sharedService.getStorage(AuthenticationService.LAST_LOGIN);
  }

  getCommonRequest({type}) {
    var request = SendActivationRequest();
    request.patientMobileNumber = this.mobileNumber;
    request.mobileNo = '0' + this.mobileNumber.toString();
    request.deviceToken = this.deviceToken;
    request.projectOutSA = this.patientOutSA == true ? true : false;
    request.loginType = this.selectedOption;
    request.oTPSendType = type == 1 ? type : 2; //this.selectedOption == 1 ? 1 : 2;
    request.zipCode = this.zipCode;

    request.logInTokenID = this.loginTokenID ?? "";

    if (this.registerd_data != null) {
      request.searchType = this.registerd_data.searchType != null ? this.registerd_data.searchType : 1;
      request.patientID = this.registerd_data.patientID != null ? this.registerd_data.patientID : 0;
      request.patientIdentificationID = request.nationalID = this.registerd_data.patientIdentificationID != null ? this.registerd_data.patientIdentificationID : '0';

      request.isRegister = this.registerd_data.isRegister;
    } else {
      request.searchType = request.searchType != null ? request.searchType : 2;
      request.patientID = this.user.patientID != null ? this.user.patientID : 0;
      request.nationalID = request.nationalID != null ? request.nationalID : '0';
      request.patientIdentificationID = request.patientIdentificationID != null ? request.patientIdentificationID : '0';
      request.isRegister = false;
    }
    request.deviceTypeID = request.searchType;
    return request;
  }

  checkActivationCode({value}) async {
    // Navigator.pop(context);
    GifLoaderDialogUtils.showMyDialog(context);
    var request = this.getCommonRequest().toJson();
    dynamic res;
    if (healthId != null) {
      request['DOB'] = dob;
      request['HealthId'] = healthId;
      request['IsHijri'] = isHijri;

      authService
          .checkActivationCodeRegister(request, value)
          .then((result) => {
                res = result,
                if (result is Map)
                  {
                    result = CheckActivationCode.fromJson(result),
                    if (this.registerd_data != null && this.registerd_data.isRegister == true)
                      {
                        widget.changePageViewIndex(1),
                        Navigator.popUntil(context, (route) => Utils.route(route, equalsTo: RegisterNew)),
                      }
                  }
                else
                  {
                    // Navigator.of(context).pop(),
                    projectViewModel.analytics.errorTracking.log('otp_verification_at_confirm_login', error: result),
                    GifLoaderDialogUtils.hideDialog(context),
                    Future.delayed(Duration(seconds: 1), () {
                      AppToast.showErrorToast(message: result);
                    }),
                  }
              })
          .catchError((err) {
        print(err);
        GifLoaderDialogUtils.hideDialog(context);
        Future.delayed(Duration(seconds: 1), () {
          AppToast.showErrorToast(message: err);
          startSMSService(tempType);
        });
      });
    } else {
      authService
          .checkActivationCode(request, value)
          .then((result) => {
                res = result,
                if (result is Map)
                  {
                    result = CheckActivationCode.fromJson(result),
                    if (this.registerd_data != null && this.registerd_data.isRegister == true)
                      {
                        widget.changePageViewIndex(1),
                        Navigator.popUntil(context, (route) => Utils.route(route, equalsTo: RegisterNew)),
                      }
                    else
                      {
                        projectViewModel.analytics.loginRegistration.login_successful(method: login_method),
                        sharedPref.remove(FAMILY_FILE),
                        result.list.isFamily = false,
                        userData = result.list,
                        sharedPref.setString(BLOOD_TYPE, result.patientBloodType),
                        authenticatedUserObject.user = result.list,
                        projectViewModel.setPrivilege(privilegeList: res),
                        sharedPref.setObject(MAIN_USER, result.list),
                        sharedPref.setObject(USER_PROFILE, result.list),
                        loginTokenID = result.logInTokenID,
                        sharedPref.setObject(LOGIN_TOKEN_ID, result.logInTokenID),
                        sharedPref.setString(TOKEN, result.authenticationTokenID),
                        checkIfUserAgreedBefore(result),
                      }
                  }
                else
                  {
                    // Navigator.of(context).pop(),
                    GifLoaderDialogUtils.hideDialog(context),
                    Future.delayed(Duration(seconds: 1), () {
                      projectViewModel.analytics.errorTracking.log('otp_verification_at_confirm_login', error: result);
                      AppToast.showErrorToast(message: result);
                      startSMSService(tempType);
                    }),
                  }
              })
          .catchError((err) {
        print(err);
        GifLoaderDialogUtils.hideDialog(context);
        Future.delayed(Duration(seconds: 1), () {
          AppToast.showErrorToast(message: err);
          startSMSService(tempType);
        });
      });
    }
  }

  checkIfUserAgreedBefore(CheckActivationCode result) {
    if (result.isNeedUserAgreement == true) {
      //move to agreement page.
    } else {
      goToHome();
    }
  }

  insertIMEI() {
    authService.insertDeviceImei(selectedOption).then((value) => {}).catchError((err) {
      print(err);
    });
  }

  getToDoCount() {
    toDoProvider.setState(0, true, "0");
    ClinicListService service = new ClinicListService();
    service.getActiveAppointmentNo(context).then((res) {
      if (res['MessageStatus'] == 1) {
        toDoProvider.setState(res['AppointmentActiveNumber'], true, "0");
      } else {}
    }).catchError((err) {
      print(err);
    });
  }

  goToHome() async {
    authenticatedUserObject.isLogin = true;
    appointmentRateViewModel.isLogin = true;
    projectViewModel.isLogin = true;
    projectViewModel.user = authenticatedUserObject.user;
    await authenticatedUserObject.getUser(getUser: true);

    // getToDoCount();

    appointmentRateViewModel
        .getIsLastAppointmentRatedList()
        .then((value) => {
              getToDoCount(),
              GifLoaderDialogUtils.hideDialog(AppGlobal.context),
              if (appointmentRateViewModel.isHaveAppointmentNotRate)
                {
                  Navigator.pushAndRemoveUntil(
                      context,
                      FadePage(
                        page: RateAppointmentDoctor(),
                      ),
                      (r) => false)
                }
              else
                {
                  Navigator.pushAndRemoveUntil(
                      context,
                      FadePage(
                        page: LandingPage(),
                      ),
                      (r) => false)
                },
              insertIMEI()
            })
        .catchError((err) {
      print(err);
    });
  }

  loading(flag) {
    setState(() {
      isLoading = flag;
    });
  }

  Widget _loginOptionButton(String _title, String _icon, int _flag, int _loginIndex) {
    bool isDisable = (_flag == 3 && !checkIfBiometricAvailable(BiometricType.face) || _flag == 2 && !checkIfBiometricAvailable(BiometricType.fingerprint));
    return InkWell(
      onTap: isDisable
          ? null
          : () {
              if (_flag == 0) {
                setState(() {
                  isMoreOption = true;
                });
              } else {
                projectViewModel.analytics.loginRegistration.verify_otp_method(method: _flag, forRegistration: widget.fromRegistration);
                authenticateUser(_flag, isActive: _loginIndex);
              }
            },
      child: Container(
        padding: EdgeInsets.only(left: 20, right: 20, bottom: 15, top: 28),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(15),
          color: isDisable ? Colors.grey.withOpacity(0.3) : Colors.white,
          border: Border.all(
            color: Color(0xffefefef),
            width: 1,
          ),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            SvgPicture.asset(
              _icon,
              height: 38,
              width: 38,
              color: isDisable ? Color(0xff2B353E).withOpacity(0.7) : null,
            ),
            Text(
              TranslationBase.of(context).verifyThrough + " " + _title,
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: isDisable ? Color(0xff2B353E).withOpacity(0.7) : Color(0xff2B353E), letterSpacing: -0.48, height: 20 / 16),
            ),
          ],
        ),
      ),
    );
  }

  // todo 'sikander' optimize this after knowing usage
  Widget getButton(int flag) {
    switch (flag) {
      case 4:
        return _loginOptionButton(TranslationBase.of(context).verifyWhatsApp, 'assets/images/new/verify_whatsapp.svg', flag, null);
        break;
      case 1:
        return _loginOptionButton(TranslationBase.of(context).verifySMS, 'assets/images/new/verify_sms.svg', flag, null);
        break;
      case 2:
        return _loginOptionButton(TranslationBase.of(context).verifyFingerprint, 'assets/images/new/verify_thumb.svg', flag, BiometricType.fingerprint.index);
        break;
      case 3:
        return _loginOptionButton(TranslationBase.of(context).verifyFaceID, 'assets/images/new/verify_face.svg', flag, BiometricType.face.index);
        break;

      default:
        return InkWell(
          onTap: () => {
            setState(() {
              isMoreOption = true;
            })
          },
          child: RoundedContainer(
            height: 150,
            backgroundColor: BiometricType.fingerprint.index == 1 ? Colors.white : Colors.white.withOpacity(.7),
            borderColor: Colors.grey,
            showBorder: true,
            child: Padding(
              padding: EdgeInsets.fromLTRB(0, 0, 0, 5),
              child: Column(
                children: <Widget>[
                  Image.asset(
                    'assets/images/login/more_icon.png',
                    height: 45,
                    width: SizeConfig.imageSizeMultiplier * 16,
                  ),
                  projectViewModel.isArabic
                      ? SizedBox(
                          height: 15,
                        )
                      : SizedBox(
                          height: 20,
                        ),
                  Texts(TranslationBase.of(context).moreVerification, fontSize: SizeConfig.textMultiplier * 1.8, textAlign: TextAlign.center, color: Colors.black)
                ],
              ),
            ),
          ),
        );
    }
  }

  getType(type, context) {
    switch (type) {
      case 1:
        return TranslationBase.of(context).verifySMS;
        break;
      case 2:
        return TranslationBase.of(context).verifyFingerprint;
        break;
      case 3:
        return TranslationBase.of(context).verifyFaceID;
        break;
      case 4:
        return TranslationBase.of(context).verifyWhatsApp;
        break;
      default:
        return TranslationBase.of(context).verifySMS;
        break;
    }
  }

  bool checkIfBiometricAvailable(BiometricType biometricType) {
    bool isAvailable = false;
    if (_availableBiometrics != null) {
      for (var i = 0; i < _availableBiometrics.length; i++) {
        if (biometricType == _availableBiometrics[i]) isAvailable = true;
      }
    }
    return isAvailable;
  }

  formatDate(date) {
    return DateFormat('MMM dd, yyy, kk:mm').format(date);
  }

  showLoader(bool isTrue) {
    setState(() {
      isLoading = isTrue;
    });
  }
}
