import 'package:flutter/gestures.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:hmg_patient_app/analytics/google-analytics.dart';
import 'package:hmg_patient_app/config/config.dart';
import 'package:hmg_patient_app/config/shared_pref_kay.dart';
import 'package:hmg_patient_app/core/service/AuthenticatedUserObject.dart';
import 'package:hmg_patient_app/core/viewModels/appointment_rate_view_model.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/locator.dart';
import 'package:hmg_patient_app/models/Appointments/toDoCountProviderModel.dart';
import 'package:hmg_patient_app/models/Authentication/check_activation_code_response.dart';
import 'package:hmg_patient_app/models/Authentication/check_paitent_authentication_req.dart';
import 'package:hmg_patient_app/models/Authentication/select_device_imei_res.dart';
import 'package:hmg_patient_app/models/Authentication/send_activation_request.dart';
import 'package:hmg_patient_app/models/InPatientServices/get_admission_info_response_model.dart';
import 'package:hmg_patient_app/models/InPatientServices/get_admission_request_info_response_model.dart';
import 'package:hmg_patient_app/new_ui/new_ext.dart';
import 'package:hmg_patient_app/new_ui/otp/otp_validation_bootmsheet_widget.dart';
import 'package:hmg_patient_app/pages/AlHabibMedicalService/health_calculator/carbs/carbs.dart';
import 'package:hmg_patient_app/pages/landing/landing_page.dart';
import 'package:hmg_patient_app/pages/login/register_new.dart';
import 'package:hmg_patient_app/pages/login/user-login-agreement-page.dart';
import 'package:hmg_patient_app/pages/rateAppointment/rate_appointment_doctor.dart';
import 'package:hmg_patient_app/services/authentication/auth_provider.dart';
import 'package:hmg_patient_app/services/clinic_services/get_clinic_service.dart';
import 'package:hmg_patient_app/theme/colors.dart';
import 'package:hmg_patient_app/uitl/app_shared_preferences.dart';
import 'package:hmg_patient_app/uitl/app_toast.dart';
import 'package:hmg_patient_app/uitl/font_utils.dart';
import 'package:hmg_patient_app/uitl/gif_loader_dialog_utils.dart';
import 'package:hmg_patient_app/uitl/translations_delegate_base.dart';
import 'package:hmg_patient_app/uitl/utils.dart';
import 'package:hmg_patient_app/widgets/others/app_scaffold_widget.dart';
import 'package:hmg_patient_app/widgets/otp/sms-popup.dart';
import 'package:hmg_patient_app/widgets/text/app_texts_widget.dart';
import 'package:hmg_patient_app/widgets/transitions/fade_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:intl/src/intl/date_format.dart';
import 'package:provider/provider.dart';

import '../../models/Authentication/authenticated_user.dart';
import '../../new_ui/exception_widget/ExceptionBottomSheet.dart';
import '../../widgets/dialogs/confirm_dialog.dart';

class WelcomeLogin extends StatefulWidget {
  @override
  _WelcomeLogin createState() => _WelcomeLogin();
}

class _WelcomeLogin extends State<WelcomeLogin> {
  bool isLoading = true;
  TextEditingController nationIdController = TextEditingController();
  TextEditingController? phoneController;
  String? phoneNumber;
  Country selectedCountry = Country.saudiArabia;

  //checkUserAuthentication();
  bool isDubai = false;
  final authService = AuthProvider();
  var sharedPref = AppSharedPreferences();
  bool authenticated = false;
  late int mobileNumber;
  String errorMsg = '';
  SelectDeviceIMEIRES? user;
  var registerd_data;
  bool isMoreOption = false;
  var zipCode;
  var patientOutSA;
  var loginTokenID;
  var loginType;
  var deviceToken;
  var lastLogin;

  AuthenticatedUser? userData;
  AuthenticatedUserObject authenticatedUserObject = locator<AuthenticatedUserObject>();
  AppointmentRateViewModel appointmentRateViewModel = locator<AppointmentRateViewModel>();
  late ProjectViewModel projectViewModel;
  final FocusNode myFocusNode = FocusNode();

  late ToDoCountProviderModel toDoProvider;

  late int selectedOption = 1;

  bool onlySMSBox = false;

  int fingrePrintBefore = 0;

  var dob;
  late int isHijri;
  var healthId;

  @override
  void initState() {
    isLoading = true;
    super.initState();
    phoneController = TextEditingController();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    projectViewModel = context.read<ProjectViewModel>();
    toDoProvider = context.read<ToDoCountProviderModel>();
    return AppScaffold(
      appBarTitle: TranslationBase.of(context).welcome,
      isShowDecPage: false,
      isShowAppBar: true,
      isshowBackButton: true,
      showNewAppBar: true,
      backgroundColor: Color(0xffF8F8F8),
      showNewAppBarTitle: false,
      showDropDown: true,
      isShowLanguageChanger: true,
      appBarIcons: [],
      dropDownList: [],
      resizeToAvoidBottomInset: true,
      dropDownIndexChange: (value) {
        Utils.changeAppLanguage(context: context);
      },
      body: GestureDetector(
        onTap: () {
          FocusScope.of(context).unfocus(); // Dismiss the keyboard when tapping outside
        },
        child: ScrollConfiguration(
          behavior: ScrollConfiguration.of(context).copyWith(overscroll: false, physics: const ClampingScrollPhysics()),
          child: NotificationListener<OverscrollIndicatorNotification>(
            onNotification: (notification) {
              notification.disallowIndicator();
              return true;
            },
            child: SingleChildScrollView(
              physics: ClampingScrollPhysics(), // Remove NeverScrollableScrollPhysics()
              padding: EdgeInsets.only(
                left: 24,
                right: 24,
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Utils.showLottie(
                      context: context,
                      assetPath: 'assets/animations/lottie/login.json',
                      width: MediaQuery.of(context).size.width * 0.45,
                      height: MediaQuery.of(context).size.height * 0.22,
                      repeat: true,
                      fit: BoxFit.cover),
                  Flexible(
                    fit: FlexFit.loose,
                    child: Container(
                      height: MediaQuery.of(context).size.height * 0.18,
                    ),
                  ),
                  Text(
                    TranslationBase.of(context).welcomeToDrSulaiman,
                    style: context.dynamicTextStyle(
                      fontSize: 28,
                      fontWeight: FontWeight.w600,
                      color: Color(0xff2B353E),
                      letterSpacing: -0.4,
                      height: 40 / 28,
                    ),
                  ),
                  SizedBox(height: 32),
                  Directionality(
                    textDirection: TextDirection.ltr,
                    child: newInputWidget(
                      TranslationBase.of(context).idNo + " / " + TranslationBase.of(context).fileNo,
                      "xxxxxxxxx",
                      nationIdController,
                      isEnable: true,
                      removePadding: true,
                      prefix: null,
                      hasSelection: false,
                      autoFocus: true,
                      isBorderAllowed: false,
                      isAllowLeadingIcon: true,
                      padding: EdgeInsets.only(top: 8, bottom: 8, left: 8, right: 8),
                      leadingIcon: "assets/images/svg/student-card.svg",
                    ),
                  ),
                  SizedBox(height: 16),
                  CustomButton(
                    text: TranslationBase.of(context).login,
                    icon: "assets/images/svg/login1.svg",
                    onPressed: () {

                      if (nationIdController.text.isNotEmpty) {
                        showModalBottomSheet(
                          context: context,
                          isScrollControlled: true,
                          isDismissible: false,
                          useSafeArea: true,
                          backgroundColor: Colors.transparent,
                          enableDrag: false,
                          // Prevent dragging to avoid focus conflicts
                          builder: (bottomSheetContext) => StatefulBuilder(builder: (BuildContext context, StateSetter setModalState) {

                            return Padding(
                              padding: EdgeInsets.only(bottom: MediaQuery.of(bottomSheetContext).viewInsets.bottom),
                              child: SingleChildScrollView(
                                child: GenericBottomSheet(
                                  countryCode: selectedCountry.countryCode,
                                  initialPhoneNumber: phoneNumber != null ? phoneNumber : "",
                                  textController: phoneController,
                                  isEnableCountryDropdown: true,
                                  onCountryChange: (value) {
                                    selectedCountry = value;
                                    setModalState(() {});
                                  },
                                  onChange: (String? value) {
                                    phoneNumber = value;
                                  },
                                  buttons: [
                                    Padding(
                                      padding: const EdgeInsets.only(bottom: 10),
                                      child: CustomButton(
                                        text: TranslationBase.of(context).sendOTPSMS,
                                        onPressed: () {
                                          int? val = Utils.onOtpBtnPressed(OTPType.sms, phoneNumber, context);
                                          if (val != null) checkUserAuthentication(val);
                                        },
                                        backgroundColor: CustomColors.bgRedColor,
                                        borderColor: CustomColors.bgRedBorderColor,
                                        textColor: Colors.white,
                                        icon: "assets/images/svg/message.svg",
                                      ),
                                    ),
                                    Row(
                                      crossAxisAlignment: CrossAxisAlignment.center,
                                      mainAxisAlignment: MainAxisAlignment.center,
                                      children: [
                                        Padding(
                                          padding: const EdgeInsets.symmetric(horizontal: 8),
                                          child: AppText(
                                            TranslationBase.of(context).oR,
                                            fontSize: 16,
                                            color: Color(0xFF2E3039),
                                            fontWeight: FontWeight.w500,
                                          ),
                                        ),
                                      ],
                                    ),
                                    Padding(
                                      padding: const EdgeInsets.only(bottom: 10, top: 10),
                                      child: CustomButton(
                                        text: TranslationBase.of(context).sendOTPWHATSAPP,
                                        onPressed: () {
                                          int? val = Utils.onOtpBtnPressed(OTPType.whatsapp, phoneNumber, context);
                                          if (val != null) checkUserAuthentication(val);
                                        },
                                        backgroundColor: Colors.white,
                                        borderColor: Color(0xFF2E3039),
                                        textColor: Color(0xFF2E3039),
                                        icon: "assets/images/svg/whatsapp.svg",
                                      ),
                                    ),
                                  ],
                                  myFocusNode: myFocusNode,
                                ),
                              ),
                            );
                          }),
                        );
                        Future.delayed(Duration(milliseconds: 500), () {
                          myFocusNode.requestFocus();
                        });
                      } else {
                        context.showBottomSheet(
                          child: ExceptionBottomSheet(
                            message: TranslationBase.of(context).pleaseEnterNationalIdOrFileNo,
                            showCancel: false,
                            onOkPressed: () {
                              Navigator.of(context).pop();
                            },
                          ),
                        );
                        // Utils.showErrorToast("Please enter National id or File no", context);
                      }
                    },
                  ),
                  SizedBox(height: 14),
                  Center(
                    child: RichText(
                      textAlign: TextAlign.center,
                      text: TextSpan(
                        style: context.dynamicTextStyle(
                          color: Colors.black,
                          fontSize: 16,
                          height: 26 / 16,
                          fontWeight: FontWeight.w500,
                        ),
                        children: <TextSpan>[
                          TextSpan(text: TranslationBase.of(context).dontHaveAccount, style: context.dynamicTextStyle()),
                          TextSpan(text: "  "),
                          TextSpan(
                            text: TranslationBase.of(context).registerNow,
                            style: context.dynamicTextStyle(
                              color: CustomColors.bgRedColor,
                              fontSize: 16,
                              height: 26 / 16,
                              fontWeight: FontWeight.w500,
                            ),
                            recognizer: TapGestureRecognizer()
                              ..onTap = () {
                                Navigator.of(context).push(FadePage(page: RegisterNew()));
                                locator<GAnalytics>().loginRegistration.visited_alhabib_group(true);
                              },
                          ),
                        ],
                      ),
                    ).withVerticalPadding(16),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  checkUserAuthentication(type) {
    // showLoader(true);
    GifLoaderDialogUtils.showMyDialog(context);
    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']),
                  loginTokenID = value['LogInTokenID'],
                  sharedPref.setObject(REGISTER_DATA_FOR_LOGIIN, request),
                  // Future.delayed(Duration(seconds: 1), () {
                  sendActivationCode(type)
                  //  })
                }
              else
                {
                  if (value['IsAuthenticated']) {checkActivationCode(onWrongActivationCode: (String? message) {})}
                }
            })
        .catchError((err) {
      print(err);
      GifLoaderDialogUtils.hideDialog(context);
      context.showBottomSheet(
          child: ExceptionBottomSheet(
        message: err.toString(),
        showCancel: true,

        onOkPressed: () {
          Navigator.of(context).pop();
          Navigator.of(context).push(FadePage(page: RegisterNew()));
        },
      ));
      projectViewModel.analytics.loginRegistration.login_fail(error: err.toString());
    });
  }

  sendActivationCode(type) async {
    var request = this.getCommonRequest(type: type);
    request.sMSSignature = await SMSOTP.getSignature();
    selectedOption = type;
    // GifLoaderDialogUtils.showMyDialog(context);
    if (healthId != null || isDubai) {
      if (!isDubai) {
        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);
        context.showBottomSheet(
            child: ExceptionBottomSheet(
          message: r.toString(),
          onOkPressed: () {
            Navigator.of(context).pop();
          },
        ));
        // AppToast.showErrorToast(message: r);
      });
    } 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);
        context.showBottomSheet(
            child: ExceptionBottomSheet(
          message: r.toString(),
          onOkPressed: () {
            Navigator.of(context).pop();
          },
        ));
        // AppToast.showErrorToast(message: r.toString());
      });
    }
  }

  Future<void> checkActivationCode({dynamic value, required Function(String? message) onWrongActivationCode}) async {
    GifLoaderDialogUtils.showMyDialog(context);
    final request = getCommonRequest().toJson();
    dynamic res;

    try {
      if (healthId != null || isDubai) {
        if (isDubai) request['DOB'] = dob;
        request['HealthId'] = healthId;
        request['IsHijri'] = isHijri;

        final result = await authService.checkActivationCodeRegister(request, value);
        res = result;

        if (result is Map) {
          final activation = CheckActivationCode.fromJson(result as Map<String, dynamic>);
          if (registerd_data?.isRegister == true) {
            Navigator.popUntil(context, (route) => Utils.route(route, equalsTo: RegisterNew));
            return;
          }
        } else {
          GifLoaderDialogUtils.hideDialog(context);
          onWrongActivationCode(result.toString());
          projectViewModel.analytics.loginRegistration.login_fail(error: result);
          projectViewModel.analytics.errorTracking.log('otp_verification_at_confirm_login', error: result);
        }
      } else {
        final result = await authService.checkActivationCode(request, value);
        res = result;

        if (result is Map) {
          final activation = CheckActivationCode.fromJson(result as Map<String, dynamic>);
          if (activation.errorCode == '699') {
            GifLoaderDialogUtils.hideDialog(context);
            onWrongActivationCode(activation.errorEndUserMessage);
            return;
          } else if (registerd_data?.isRegister == true) {
            Navigator.popUntil(context, (route) => Utils.route(route, equalsTo: RegisterNew));
            return;
          } else {
            sharedPref.remove(FAMILY_FILE);
            activation.list!.isFamily = false;
            userData = activation.list;
            sharedPref.setString(BLOOD_TYPE, activation.patientBloodType ?? "");
            authenticatedUserObject.user = activation.list!;
            projectViewModel.setPrivilege(privilegeList: res);
            await sharedPref.setObject(MAIN_USER, activation.list);
            await sharedPref.setObject(USER_PROFILE, activation.list);
            loginTokenID = activation.logInTokenID;
            await sharedPref.setObject(LOGIN_TOKEN_ID, activation.logInTokenID);
            await sharedPref.setString(TOKEN, activation.authenticationTokenID!);
            checkIfUserAgreedBefore(activation);
            projectViewModel.analytics.loginRegistration.login_successful();
          }
        } else {
          GifLoaderDialogUtils.hideDialog(context);
          onWrongActivationCode(result.toString());
          // context.showBottomSheet(
          //   child: ExceptionBottomSheet(
          //     message: result.toString(),
          //     onOkPressed: () {
          //       Navigator.of(context).pop();
          //     },
          //   ),
          // );
          projectViewModel.analytics.loginRegistration.login_fail(error: result);
          projectViewModel.analytics.errorTracking.log('otp_verification_at_confirm_login', error: result);
        }
      }
    } catch (err) {
      GifLoaderDialogUtils.hideDialog(context);
      onWrongActivationCode(err.toString());
      // context.showBottomSheet(
      //   child: ExceptionBottomSheet(
      //     message: err.toString(),
      //     onOkPressed: () {
      //       Navigator.of(context).pop();
      //     },
      //   ),
      // );
    }
  }

  void startSMSService(int type) {
    late SMSOTP smsOtp;
    smsOtp = SMSOTP(
      context,
      type,
      phoneNumber,
      (code) {
        // smsOtp.dispose();
        checkActivationCode(
            value: code,
            onWrongActivationCode: (String? message) {
              smsOtp.clearOTPInput(); // Clear the SMS code when wrong
              context.showBottomSheet(
                child: ExceptionBottomSheet(
                  message: message.toString(),
                  onOkPressed: () {
                    Navigator.of(context).pop();
                    // Don't resume timer here, let it continue naturally when user tries again
                  },
                ),
              );
            });
      },
      () {
        // smsOtp.dispose();
        Navigator.pop(context);
      },
    );
    smsOtp.displayDialog(context);
  }

  Future<void> setDefault() async {
    // Load user data from shared preferences
    final imeiUserData = await sharedPref.getObject(IMEI_USER_DATA);
    if (imeiUserData != null) {
      user = SelectDeviceIMEIRES.fromJson(imeiUserData);
    }

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

    mobileNumber = registerd_data?.patientMobileNumber ?? int.parse(user?.mobile ?? '0');
    zipCode = registerd_data?.zipCode ?? (user?.outSA == true ? "971" : "966");
    patientOutSA = registerd_data != null ? (registerd_data.zipCode == "966" ? 0 : 1) : user?.outSA;

    if (registerd_data != null) {
      loginTokenID = await sharedPref.getString(LOGIN_TOKEN_ID);
      loginType = registerd_data.searchType;
    }

    final nhic = await sharedPref.getObject(NHIC_DATA);
    if (nhic != null) {
      final dateFormat = DateFormat('MM/dd/yyyy');
      final dateFormat2 = DateFormat('dd/MM/yyyy');
      dob = nhic['IsHijri'] ? nhic['DateOfBirth'] : dateFormat2.format(dateFormat.parse(nhic['DateOfBirth']));
      isHijri = nhic['IsHijri'] ? 1 : 0;
      healthId = nhic['HealthId'];
    }

    deviceToken = await sharedPref.getString(PUSH_TOKEN);
    final lastLoginPref = await sharedPref.getInt(LAST_LOGIN);
    lastLogin = lastLoginPref ?? user?.logInType;

    GifLoaderDialogUtils.hideDialog(context);
  }

  getCommonRequest({type}) {
    bool fileNo = false;
    if (nationIdController.text != null && nationIdController.text.isNotEmpty) {
      fileNo = nationIdController.text.length < 10;
    }

    var request = SendActivationRequest();
    request.patientMobileNumber = int.parse(phoneNumber!);
    request.mobileNo = '0' + phoneNumber.toString();
    request.deviceToken = this.deviceToken;
    request.projectOutSA = this.patientOutSA == true ? true : false;
    request.loginType = type == 1 ? type : 2;
    request.oTPSendType = type == 1 ? type : 2; //this.selectedOption == 1 ? 1 : 2;
    request.zipCode = selectedCountry.countryCode;

    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.dob = this.registerd_data.dob;
      request.isRegister = this.registerd_data.isRegister;
    } else {
      // request.searchType = request.searchType != null ? request.searchType : 1;
      if (fileNo) {
        request.patientID = this.user != null && this.user!.patientID != null ? this.user!.patientID : int.parse(nationIdController.text);
        request.patientIdentificationID = request.nationalID = "";
        request.searchType = 2;
      } else {
        request.patientID = 0;
        request.searchType = 1;
        request.patientIdentificationID = request.nationalID = nationIdController != null ? nationIdController.text : '0';
      }
      request.isRegister = false;
    }
    request.deviceTypeID = request.searchType;
    return request;
  }

  checkIfUserAgreedBefore(CheckActivationCode result) {
    if (projectViewModel.havePrivilege(109)) {
      this.authService.checkIfUserAgreed().then((result) {
        if (result['IsPatientAlreadyAgreed']) {
          goToHome();
        } else {
          this.authService.getUserAgreementContent().then((result) {
            GifLoaderDialogUtils.hideDialog(AppGlobal.context);
            Navigator.pushAndRemoveUntil(
                context,
                FadePage(
                  page: UserLoginAgreementPage(
                    userAgreementText: result['UserAgreementContent'],
                    authenticatedUserObject: authenticatedUserObject,
                    appointmentRateViewModel: appointmentRateViewModel,
                    selectedOption: selectedOption,
                    isArabic: projectViewModel.isArabic,
                  ),
                ),
                (r) => false);
          }).catchError((err) {
            GifLoaderDialogUtils.hideDialog(context);
            context.showBottomSheet(
                child: ExceptionBottomSheet(
              message: err.toString(),
              onOkPressed: () {
                Navigator.of(context).pop();
              },
            ));
            // print(err);
          });
        }
      }).catchError((err) {
        GifLoaderDialogUtils.hideDialog(context);
        // context.showBottomSheet(
        //     child: ExceptionBottomSheet(
        //   message: err.toString(),
        //   onOkPressed: () {
        //     Navigator.of(context).pop();
        //   },
        // ));
        // print(err);
      });
    } else {
      goToHome();
    }
  }

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

    getToDoCount();
    checkIfIsInPatient();

    appointmentRateViewModel.getIsLastAppointmentRatedList(projectViewModel.isArabic ? 1 : 2).then((_) {
      GifLoaderDialogUtils.hideDialog(AppGlobal.context);

      if (appointmentRateViewModel.isHaveAppointmentNotRate) {
        Navigator.pushAndRemoveUntil(
          context,
          FadePage(page: RateAppointmentDoctor()),
          (route) => false,
        );
      } else {
        Navigator.pushAndRemoveUntil(
          context,
          FadePage(page: LandingPage()),
          (route) => false,
        );
      }
      insertIMEI();
    }).catchError((error) {
      // context.showBottomSheet(
      //     child: ExceptionBottomSheet(
      //   message: error.toString(),
      //   onOkPressed: () {
      //     Navigator.of(context).pop();
      //   },
      // ));
    });
  }

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

  insertIMEI() {
    authService.insertDeviceImei(selectedOption).then((value) => {}).catchError((err) {
      // context.showBottomSheet(
      //     child: ExceptionBottomSheet(
      //   message: err.toString(),
      //   onOkPressed: () {
      //     Navigator.of(context).pop();
      //   },
      // ));
      // print(err);
    });
  }

  void checkIfIsInPatient() {
    final service = ClinicListService();
    service.checkIfInPatientAPI(context).then((res) {
      if (res['MessageStatus'] != 1) return;

      final isAdmitted = res['isAdmitted'] == true;
      final hasAdmissionRequest = res['hasAdmissionRequests'] == true;

      print("IS ADMITTED: $isAdmitted");
      print("Has Admission Request: $hasAdmissionRequest");

      if (isAdmitted && res['PatientAdmittedInformation']?.isNotEmpty == true) {
        final info = GetAdmissionInfoResponseModel.fromJson(res['PatientAdmittedInformation'][0]);
        projectViewModel.setInPatientProjectID(res['PatientAdmittedInformation'][0]['ProjectID']);
        projectViewModel.setInPatientAdmissionInfo(info);
        projectViewModel.setIsPatientAdmitted(true);
      }

      if (hasAdmissionRequest && res['MedicalInstruction']?.isNotEmpty == true) {
        final reqInfo = GetAdmissionRequestInfoResponseModel.fromJson(res['MedicalInstruction'][0]);
        projectViewModel.setInPatientProjectID(res['MedicalInstruction'][0]['projectId']);
        projectViewModel.setInPatientAdmissionRequest(reqInfo);
        projectViewModel.setPatientHasAdmissionRequest(true);
      }
    });
  }
}
