import 'dart:convert';

import 'package:flutter/gestures.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:hijri_gregorian_calendar/hijri_gregorian_calendar.dart';
import 'package:hmg_patient_app/config/config.dart';
import 'package:hmg_patient_app/config/shared_pref_kay.dart';
import 'package:hmg_patient_app/config/size_config.dart';
import 'package:hmg_patient_app/core/service/client/base_app_client.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.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/check_user_status_reponse.dart';
import 'package:hmg_patient_app/models/Authentication/check_user_status_req.dart';
import 'package:hmg_patient_app/models/Authentication/checkpatient_for_registration.dart';
import 'package:hmg_patient_app/models/Authentication/register_info_response.dart';
import 'package:hmg_patient_app/models/Authentication/send_activation_request.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/login/login-type.dart';
import 'package:hmg_patient_app/pages/login/register-info.dart';
import 'package:hmg_patient_app/pages/login/register.dart';
import 'package:hmg_patient_app/pages/login/register_new_step_2.dart';
import 'package:hmg_patient_app/pages/login/user-login-agreement-page.dart';
import 'package:hmg_patient_app/pages/login/welcome.dart';
import 'package:hmg_patient_app/services/authentication/auth_provider.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/uitl/utils_new.dart';
import 'package:hmg_patient_app/widgets/drawer/langauge_picker.dart';
import 'package:hmg_patient_app/widgets/others/app_scaffold_widget.dart';
import 'package:flutter/material.dart';
import 'package:hmg_patient_app/widgets/otp/sms-popup.dart';
import 'package:hmg_patient_app/widgets/text/app_texts_widget.dart';
import 'package:provider/provider.dart';

import '../../core/viewModels/appointment_rate_view_model.dart';
import '../../locator.dart';
import '../../models/Authentication/authenticated_user.dart';
import '../../models/Authentication/select_device_imei_res.dart';
import '../../models/InPatientServices/get_admission_info_response_model.dart';
import '../../models/InPatientServices/get_admission_request_info_response_model.dart';
import '../../new_ui/exception_widget/ExceptionBottomSheet.dart';
import '../../services/clinic_services/get_clinic_service.dart';
import '../../widgets/dialogs/alert_dialog.dart';
import '../../widgets/dialogs/confirm_dialog.dart';
import '../../widgets/transitions/fade_page.dart';
import 'package:intl/intl.dart' as intl;

import '../landing/landing_page.dart';
import '../rateAppointment/rate_appointment_doctor.dart';

class RegisterNew extends StatefulWidget {
  @override
  _RegisterNew createState() => _RegisterNew();
}

class _RegisterNew extends State<RegisterNew> {
  final nationalIDorFile = TextEditingController();
  final phoneController = TextEditingController();
  AppointmentRateViewModel appointmentRateViewModel = locator<AppointmentRateViewModel>();
  final FocusNode myFocusNode = FocusNode();
  Country selectedCountry = Country.saudiArabia;
  OTPType? otpType;
  bool isTermsAccepted = false;
  DateTime? selectedDOB;
  CheckUserStatusResponse? nHICData;

  final int loginType = LoginType.loginType;
  String mobileNo = '';
  var loginTokenID;

  // String countryCode = '966';
  var isHijri;

  final util = Utils();
  bool isButtonDisabled = true;
  final authService = new AuthProvider();
  final sharedPref = new AppSharedPreferences();
  late PageController _controller;
  late bool isLoading;
  String? LoginTokenID;
  bool isDubai = false;
  final intl.DateFormat dateFormat = intl.DateFormat('dd/MM/yyyy');
  SelectDeviceIMEIRES? user;
  AuthenticatedUser? userdata;
  late int selectedOption;
  bool isSkipRegistration = false;

  late ProjectViewModel projectViewModel;
  late ToDoCountProviderModel toDoProvider;

  @override
  void initState() {
    super.initState();
    _controller = new PageController();
  }

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

  changePageViewIndex(pageIndex) {
    _controller.jumpToPage(pageIndex);
  }

  @override
  Widget build(BuildContext context) {
    projectViewModel = context.read<ProjectViewModel>();
    toDoProvider = context.read<ToDoCountProviderModel>();
    return AppScaffold(
        appBarTitle: TranslationBase.of(context).register,
        isShowDecPage: false,
        isShowAppBar: true,
        isshowBackButton: true,
        showNewAppBar: true,
        backgroundColor: Color(0xffF8F8F8),
        showNewAppBarTitle: false,
        showDropDown: true,
        isShowLanguageChanger: true,
        appBarIcons: [],
        dropDownList: [],
        extendBody: true,

        resizeToAvoidBottomInset: true,
        dropDownIndexChange: (value) {
          Utils.changeAppLanguage(context: context);
        },
        body: GestureDetector(
          onTap: () {
            FocusScope.of(context).unfocus();
          },
          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(),
                padding: EdgeInsets.only(
                  left: 24,
                  right: 24,
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Utils.showLottie(
                        context: context,
                        assetPath: 'assets/animations/lottie/register.json',
                        width: MediaQuery.of(context).size.width * 0.45,
                        height: MediaQuery.of(context).size.height * 0.22,
                        fit: BoxFit.cover,
                        repeat: true),
                    SizedBox(height: 8),
                    Text(
                      TranslationBase.of(context).prepareToElevate,
                      textScaler: TextScaler.linear(MediaQuery.textScalerOf(context).scale(1)),
                      style: context.dynamicTextStyle(
                        fontSize: 28,
                        fontWeight: FontWeight.w600,
                        color: Color(0xff2B353E),
                        letterSpacing: -0.4,
                        height: 40 / 28,
                      ),
                    ),
                    SizedBox(height: 24),
                    Directionality(
                      textDirection: Directionality.of(context),
                      child: Container(
                        decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(24)),
                        padding: EdgeInsets.only(left: 16, right: 16, top: 0, bottom: 0),
                        child: Column(
                          children: [
                            Directionality(
                              textDirection: TextDirection.ltr,
                              child: newInputWidget(
                                TranslationBase.of(context).country,
                                TranslationBase.of(context).ksa,
                                nationalIDorFile,
                                isEnable: true,
                                prefix: null,
                                hasSelection: true,
                                dropdownItems: Country.values.map((e) => context.selectedLanguage == "ar" ? e.nameArabic : e.displayName).toList(),
                                selectedValue: context.selectedLanguage == "ar" ? selectedCountry.nameArabic : selectedCountry.displayName,
                                selectionType: SelectionType.dropdown,
                                onChange: (val) {
                                  if (val != null) {
                                    print(val);
                                    setState(() {
                                      selectedCountry = CountryExtension.fromDisplayName(val);
                                    });
                                  }
                                },
                                isBorderAllowed: false,
                                isAllowLeadingIcon: true,
                                hasSelectionCustomIcon: true,
                                removePadding: true,
                                isLeadingCountry: true,
                                isAllowRadius: false,
                                padding: const EdgeInsets.only(top: 8, bottom: 8, left: 0, right: 0),
                                selectionCustomIcon: "assets/images/svg/arrow-down.svg",
                                leadingIcon: selectedCountry.iconPath,
                              ).withVerticalPadding(8),
                            ),
                            Divider(height: 1),
                            Directionality(
                              textDirection: TextDirection.ltr,
                              child: newInputWidget(TranslationBase.of(context).nationalIdNumber, "xxxxxxxxx", nationalIDorFile,
                                  isEnable: true,
                                  prefix: null,
                                  removePadding: true,
                                  isAllowRadius: false,
                                  hasSelection: false,
                                  isBorderAllowed: false,
                                  isAllowLeadingIcon: true,
                                  autoFocus: true,
                                  padding: const EdgeInsets.only(top: 8, bottom: 8, left: 0, right: 0),
                                  leadingIcon: "assets/images/svg/student-card.svg", onChange: (value) {
                                print(value);
                              }).withVerticalPadding(8),
                            ),
                            Divider(height: 1),
                            Directionality(
                              textDirection: TextDirection.ltr,
                              child: newInputWidget(TranslationBase.of(context).dob, "11 July, 1994", nationalIDorFile,
                                  isEnable: true,
                                  prefix: null,
                                  hasSelection: true,
                                  removePadding: true,
                                  isBorderAllowed: false,
                                  isAllowLeadingIcon: true,
                                  hasSelectionCustomIcon: true,
                                  selectionType: SelectionType.calendar,
                                  selectedValue: selectedDOB != null
                                      ? isHijri == 1
                                          ? Utils.formatHijriDateToDisplay(selectedDOB!.toIso8601String())
                                          : Utils.formatDateToDisplay(selectedDOB.toString())
                                      : null,
                                  selectionCustomIcon: "assets/images/svg/calendar.svg",
                                  lang: context.selectedLanguage,
                                  padding: const EdgeInsets.only(top: 8, bottom: 8, left: 0, right: 0),
                                  leadingIcon: "assets/images/svg/birthday-cake.svg", onChange: (value) {
                                selectedDOB = DateTime.parse(value!);
                                if (isHijri == 1) {
                                  var hijriDate = HijriGregConverter.gregorianToHijri(DateTime.parse(value));
                                  selectedDOB = DateTime(hijriDate.year, hijriDate.month, hijriDate.day);
                                } else {
                                  selectedDOB = DateTime.parse(value);
                                }
                                print(selectedDOB!.toIso8601String());
                                setState(() {});
                              }, onCalendarTypeChanged: (bool value) {
                                if (value) {
                                  isHijri = 0;
                                } else {
                                  isHijri = 1;
                                }
                              }).withVerticalPadding(8),
                            ),
                          ],
                        ),
                      ),
                    ),
                    SizedBox(height: 25),
                    GestureDetector(
                      onTap: () {
                        setState(() {
                          isTermsAccepted = !isTermsAccepted;
                        });
                      },
                      child: Row(
                        children: [
                          AnimatedContainer(
                            duration: const Duration(milliseconds: 200),
                            height: 24,
                            width: 24,
                            decoration: BoxDecoration(
                              color: isTermsAccepted ? const Color(0xFFE92227) : Colors.transparent,
                              borderRadius: BorderRadius.circular(6),
                              border: Border.all(
                                color: isTermsAccepted ? const Color(0xFFE92227) : Colors.grey,
                                width: 2,
                              ),
                            ),
                            child: isTermsAccepted ? const Icon(Icons.check, size: 16, color: Colors.white) : null,
                          ),
                          SizedBox(width: 12),
                          Expanded(
                            child: Text(
                              TranslationBase.of(context).iAcceptTermsConditions,
                              style: context.dynamicTextStyle(fontSize: 14, fontWeight: FontWeight.w500, color: Color(0xFF2E3039)),
                            ),
                          ),
                        ],
                      ),
                    ),
                    SizedBox(height: 25),
                    CustomButton(
                      text: TranslationBase.of(context).register,
                      icon: "assets/images/svg/note-edit.svg",
                      onPressed: () {
                        // bool isValid = Utils.validateIqama(nationalIDorFile.text);
                        if (nationalIDorFile == null || nationalIDorFile.text.isEmpty) {
                          context.showBottomSheet(
                            child: ExceptionBottomSheet(
                              message: TranslationBase.of(context).pleaseEnterNationalId,
                              showCancel: false,
                              onOkPressed: () {
                                Navigator.of(context).pop();
                              },
                            ),
                          );
                          // Utils.showErrorToast(TranslationBase.of(context).pleaseEnterNationalId);
                          return;
                        }
                        if ((!Utils.validateIqama(nationalIDorFile.text) && selectedCountry.countryCode == '966') ||
                            (!Utils.validateUaeNationalId(nationalIDorFile.text) && selectedCountry.countryCode == '971')) {
                          context.showBottomSheet(
                            child: ExceptionBottomSheet(
                              message: TranslationBase.of(context).incorrectNationalId,
                              showCancel: false,
                              onOkPressed: () {
                                Navigator.of(context).pop();
                              },
                            ),
                          );
                          return;
                        }
                        if (selectedCountry == null || selectedCountry.countryCode.isEmpty) {
                          context.showBottomSheet(
                            child: ExceptionBottomSheet(
                              message: TranslationBase.of(context).pleaseSelectCountry,
                              showCancel: false,
                              onOkPressed: () {
                                Navigator.of(context).pop();
                              },
                            ),
                          );
                          return;
                        }

                        if (selectedDOB == null) {
                          context.showBottomSheet(
                            child: ExceptionBottomSheet(
                              message: TranslationBase.of(context).pleaseSelectDOB,
                              showCancel: false,
                              onOkPressed: () {
                                Navigator.of(context).pop();
                              },
                            ),
                          );
                          return;
                        }
                        if (!isTermsAccepted) {
                          context.showBottomSheet(
                            child: ExceptionBottomSheet(
                              message: TranslationBase.of(context).pleaseAcceptTermsConditions,
                              showCancel: false,
                              onOkPressed: () {
                                Navigator.of(context).pop();
                              },
                            ),
                          );
                          return;
                        }

                        if (phoneController != null) {
                          phoneController.clear();
                        }
                        showModalBottomSheet(
                          context: context,
                          isScrollControlled: true,
                          isDismissible: false,
                          backgroundColor: Colors.transparent,
                          builder: (bottomSheetContext) => Padding(
                            padding: EdgeInsets.only(bottom: MediaQuery.of(bottomSheetContext).viewInsets.bottom),
                            child: SingleChildScrollView(
                              child: GenericBottomSheet(
                                countryCode: selectedCountry.countryCode,
                                initialPhoneNumber: "",
                                textController: phoneController,
                                onChange: (String? value) {
                                  mobileNo = value!;
                                },
                                buttons: [
                                  Padding(
                                    padding: const EdgeInsets.only(bottom: 10),
                                    child: CustomButton(
                                      text: TranslationBase.of(context).sendOTPSMS,
                                      onPressed: () {
                                        if (mobileNo.isEmpty) {
                                          context.showBottomSheet(
                                            child: ExceptionBottomSheet(
                                              message: TranslationBase.of(context).pleaseEnterMobile,
                                              showCancel: false,
                                              onOkPressed: () {
                                                Navigator.of(context).pop();
                                              },
                                            ),
                                          );
                                        }
                                       else if (!Utils.validateMobileNumber(mobileNo)) {
                                          context.showBottomSheet(
                                            child: ExceptionBottomSheet(
                                              message:  TranslationBase.of(context).pleaseEnterValidMobile,
                                              showCancel: false,
                                              onOkPressed: () {
                                                Navigator.of(context).pop();
                                              },
                                            ),
                                          );
                                        }
                                        else {
                                          registerUser(1);
                                        }
                                      },
                                      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,
                                          fontFamily: context.fontFamily,
                                          color: Color(0xFF2E3039),
                                          fontWeight: FontWeight.w500,
                                        ),
                                      ),
                                    ],
                                  ),
                                  Padding(
                                    padding: const EdgeInsets.only(bottom: 10, top: 10),
                                    child: CustomButton(
                                      text: TranslationBase.of(context).sendOTPWHATSAPP,
                                      onPressed: () {
                                        if (mobileNo.isEmpty) {
                                          context.showBottomSheet(
                                            child: ExceptionBottomSheet(
                                              message:  TranslationBase.of(context).pleaseEnterMobile,
                                              showCancel: false,
                                              onOkPressed: () {
                                                Navigator.of(context).pop();
                                              },
                                            ),
                                          );
                                        }   else if (!Utils.validateMobileNumber(mobileNo)) {
                                          context.showBottomSheet(
                                            child: ExceptionBottomSheet(
                                              message:  TranslationBase.of(context).pleaseEnterValidMobile,
                                              showCancel: false,
                                              onOkPressed: () {
                                                Navigator.of(context).pop();
                                              },
                                            ),
                                          );
                                        } else {
                                          registerUser(4);
                                        }
                                        // int? val = Utils.onOtpBtnPressed(OTPType.whatsapp, mobileNo, context);
                                        // registerUser(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();
                        });
                      },
                      fontFamily: context.fontFamily,
                    ),
                    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).alreadyHaveAccount, style: context.dynamicTextStyle()),
                            TextSpan(text: "  "),
                            TextSpan(
                              text: TranslationBase.of(context).loginNow,
                              style: context.dynamicTextStyle(
                                color: CustomColors.bgRedColor,
                                fontSize: 16,
                                height: 26 / 16,
                                fontWeight: FontWeight.w500,
                              ),
                              recognizer: TapGestureRecognizer()
                                ..onTap = () {
                                  Navigator.of(context).pop();
                                },
                            ),
                          ],
                        ),
                      ),
                    ),
                    SizedBox(height: 30),
                  ],
                ),
              ),
            ),
          ),
        ));
  }

  Widget showProgress({String? title, String? status, Color? color, bool isNeedBorder = true}) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Container(
                  width: 26,
                  height: 26,
                  decoration: containerRadius(color!, 200),
                  child: Icon(
                    Icons.done,
                    color: Colors.white,
                    size: 16,
                  ),
                ),
                if (isNeedBorder)
                  Expanded(
                      child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: mDivider(Colors.grey),
                  )),
              ],
            ),
            mHeight(8),
            Text(
              title!,
              style: TextStyle(
                fontSize: 11,
                fontWeight: FontWeight.w600,
                letterSpacing: -0.44,
              ),
            ),
            mHeight(2),
            Container(
              padding: EdgeInsets.all(5),
              decoration: containerRadius(color.withOpacity(0.2), 4),
              child: Text(
                status!,
                style: TextStyle(
                  fontSize: 8,
                  fontWeight: FontWeight.w600,
                  letterSpacing: -0.32,
                  color: color,
                ),
              ),
            ),
          ],
        )
      ],
    );
  }

  void registerUser(int? value) {
    otpType = value == 1 ? OTPType.sms : OTPType.whatsapp;
    if (value == 1) {
      print("OTP sent successfully to ${mobileNo} using SMS");
    } else {
      print("OTP sent successfully to ${mobileNo} using Whatsapp");
    }
    startRegistration(value);
  }

  startRegistration(type) {
    var request = CheckPatientForRegistration();

    request.patientMobileNumber = int.parse(mobileNo);
    request.zipCode = selectedCountry.countryCode;
    request.patientOutSA = selectedCountry.countryCode == '966' ? 0 : 1;
    request.patientIdentificationID = int.parse(nationalIDorFile.text);
    request.patientID = 0;
    request.isRegister = true;
    request.dob = isHijri == 1 ? selectedDOB!.toString() : dateFormat.format(selectedDOB!);
    request.isHijri = isHijri ?? 0;
    checkPatientForRegistration(registrationData: request, type: type);
    // }
  }

  checkPatientForRegistration({required CheckPatientForRegistration registrationData, type}) {
    int languageID = Provider.of<ProjectViewModel>(context, listen: false).isArabic ? 1 : 2;
    GifLoaderDialogUtils.showMyDialog(context);
    authService
        .checkPatientForRegisteration(registrationData, languageID)
        .then((response) => {
              // Keep loader active, continue to next step
              checkUserStatus(response, registrationData, type)
            })
        .catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      // context.showBottomSheet(
      //   child: ExceptionBottomSheet(
      //     showCancel: true,
      //     message: err,
      //     onOkPressed: () {
      //       Navigator.of(context).pop();
      //       Navigator.of(context).push(FadePage(page: RegisterNew()));
      //     },
      //   ),
      // );
    });
  }

  checkUserStatus(response, CheckPatientForRegistration request, type) async {
    // No loader shown here since it's already hidden in checkPatientForRegisteration
    if (response is Map) {
      var nRequest = request.toJson();
      nRequest['LogInTokenID'] = response['LogInTokenID'];
      if (response['hasFile'] == true) {
        GifLoaderDialogUtils.hideDialog(context);
        context.showBottomSheet(
          child: ExceptionBottomSheet(
            message: response['ErrorEndUserMessage'],
            showCancel: true,
            onOkPressed: () {
              // AlertDialogBox.closeAlertDialog(context);
              sharedPref.setObject(REGISTER_DATA_FOR_LOGIIN, nRequest);
              setState(() {
                isSkipRegistration = true;
              });
              Navigator.of(context).pop();
              sendActivationCode(type, "", null, isSkipRegistration);
            },
          ),
        );
      } else {
        final intl.DateFormat dateFormat = intl.DateFormat('dd/MM/yyyy');
        nRequest['forRegister'] = true;
        nRequest['isRegister'] = true;
        nRequest["PatientIdentificationID"] = nRequest["PatientIdentificationID"].toString();
        request.dob = isHijri == 1 ? selectedDOB!.toString() : dateFormat.format(selectedDOB!);
        nRequest['isHijri'] = isHijri;
        sharedPref.setObject(REGISTER_DATA_FOR_LOGIIN, nRequest);
        sharedPref.setString(LOGIN_TOKEN_ID, response['LogInTokenID']);
        if (request.patientOutSA == 0) {
          this.chekUserData(response['LogInTokenID'], type);
        } else {
          sendActivationCode(type, response['LogInTokenID'], null, isSkipRegistration);
        }
      }
    } else {
      GifLoaderDialogUtils.hideDialog(context);
      // if (response['ErrorCode'] == '-986') {
      //AppToast.showErrorToast(message: response);
      GifLoaderDialogUtils.hideDialog(context);
      context.showBottomSheet(
        child: ExceptionBottomSheet(
          message: response,
          onOkPressed: () {
            Navigator.of(context).pop();
          },
        ),
      );
    }
  }

  chekUserData(loginToken, int type) {
    // Keep existing loader active, don't show new one
    var request = CheckUserStatusRequest();
    request.patientIdentificationID = nationalIDorFile.text;
    request.dOB = isHijri == 1 ? selectedDOB!.toString() : dateFormat.format(selectedDOB!);
    request.isHijri = isHijri;
    request.patientOutSA = selectedCountry.countryCode == '966' ? 0 : 1;

    this.authService.checkUserStatus(request).then((result) {
      // Keep loader active, continue to next step
      if (result is Map) {
        RegisterInfoResponse? resultSet;
        CheckUserStatusResponse res = CheckUserStatusResponse.fromJson(result as Map<String, dynamic>);
        nHICData = res;
        sharedPref.setObject(NHIC_DATA, res.toJson());
        resultSet = RegisterInfoResponse.fromJson(res.toJson());

        sendActivationCode(type, loginToken, resultSet, isSkipRegistration);
      } else {
        GifLoaderDialogUtils.hideDialog(context);
        context.showBottomSheet(
          child: ExceptionBottomSheet(
            message: result != null ? result : TranslationBase.of(context).somethingWentWrong,
            showCancel: false,
            onOkPressed: () {
              Navigator.of(context).pop();
            },
          ),
        );
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      context.showBottomSheet(
        child: ExceptionBottomSheet(
          message: err.toString(),
          showCancel: false,
          onOkPressed: () {
            Navigator.of(context).pop();
          },
        ),
      );
    });
  }

  sendActivationCode(type, loginTokenID, RegisterInfoResponse? nHICData, skipRegistration) async {
    LoginTokenID = loginTokenID;
    var request = authService.getCommonRequest(
        registerd_data: null,
        deviceToken: skipRegistration ? null : DEVICE_TOKEN,
        mobileNumber: int.parse(mobileNo),
        zipCode: selectedCountry.countryCode,
        patientOutSA: selectedCountry.countryCode == "966" ? 0 : 1,
        loginTokenID: LoginTokenID,
        selectedOption: type,
        type: type,
        user: SelectDeviceIMEIRES());
    request.isRegister = true;
    request.dob = isHijri == 1 ? selectedDOB!.toString() : dateFormat.format(selectedDOB!);
    request.sMSSignature = await SMSOTP.getSignature();
    print("Otp Send Type =" + request.oTPSendType.toString());

    if (selectedCountry.countryCode == "966" && !skipRegistration) {
      request.healthId = nHICData!.healthId;
      request.nationalID = nHICData.idNumber;
      request.patientIdentificationID = nHICData.idNumber;
    } else {
      request.nationalID = nationalIDorFile.text;
      request.patientIdentificationID = nationalIDorFile.text;
    }
    request.isHijri = isHijri ?? 0;

    if (skipRegistration) {
      // Keep existing loader active, don't show new one
      var req = getCommonRequest(type: type);
      req.logInTokenID = "";
      var request = CheckPatientAuthenticationReq.fromJson(req.toJson());
      GifLoaderDialogUtils.showMyDialog(context);
      authService.checkPatientAuthentication(request).then((value) async {
        if (value['isSMSSent']) {
          sharedPref.setString(LOGIN_TOKEN_ID, value['LogInTokenID']);
          LoginTokenID = value['LogInTokenID'];
          var request = this.getCommonRequest(type: type);
          request.sMSSignature = await SMSOTP.getSignature();
          selectedOption = type;
          request.dob = "";
          request.healthId = "";
          request.isHijri = 0;

          await authService.sendActivationCode(request).then((result) {
            // Hide loader before navigation to SMS OTP
            GifLoaderDialogUtils.hideDialog(context);
            if (result != null && result['isSMSSent'] == true) {
              startSMSService(request.loginType, skipRegistration);
            }
          }).catchError((r) {
            GifLoaderDialogUtils.hideDialog(context);
            context.showBottomSheet(
              child: ExceptionBottomSheet(
                message: r.toString(),
                showCancel: false,
                onOkPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            );
          });
        } else {
          if (value['IsAuthenticated']) {
            // Keep loader active and proceed to checkActivationCode
            checkActivationCode(onWrongActivationCode: (String? message, bool? isReroute) {
              GifLoaderDialogUtils.hideDialog(context);
            });
          } else {
            GifLoaderDialogUtils.hideDialog(context);
          }
        }
      }).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()));
            },
          ),
        );
      });
    } else {
      // Keep existing loader active, don't show new one
      await this.authService.sendActivationCodeRegister(request).then((result) {
        // Hide loader before navigation to SMS OTP
        GifLoaderDialogUtils.hideDialog(context);
        if (result != null && result['isSMSSent'] == true) {
          print(result);
          startSMSService(type, skipRegistration);
        }
      }).catchError((r) {
        GifLoaderDialogUtils.hideDialog(context);
        context.showBottomSheet(
          child: ExceptionBottomSheet(
            message: r.toString(),
            showCancel: false,
            onOkPressed: () {
              Navigator.of(context).pop();
            },
          ),
        );
      });
    }
  }

  Future<void> checkActivationCode({value, type, skipRegistration, required Function(String? message, bool? isReroute) onWrongActivationCode}) async {
    final isSaudi = selectedCountry.countryCode == "966";
    final isHijriDate = isHijri == 1;
    final dobString = isHijriDate ? selectedDOB!.toString() : dateFormat.format(selectedDOB!);
    var req;
    GifLoaderDialogUtils.showMyDialog(context);
    if (skipRegistration) {
      req = getCommonRequest(type: type);
    } else {
      req = authService.getCommonRequest(
        registerd_data: null,
        deviceToken: DEVICE_TOKEN,
        mobileNumber: int.parse(mobileNo),
        zipCode: selectedCountry.countryCode,
        patientOutSA: isSaudi ? 0 : 1,
        loginTokenID: LoginTokenID,
        selectedOption: type,
        user: SelectDeviceIMEIRES(),
      );
    }
    req.dob = dobString;
    req.isHijri = isHijri ?? 0;

    if (isSaudi && !skipRegistration) {
      req.healthId = nHICData?.healthId ?? "";
    } else {
      req.healthId = "";
    }

    if (!skipRegistration) {
      req.nationalID = isSaudi ? nHICData?.idNumber : nationalIDorFile.text;
      req.patientIdentificationID = isSaudi ? nHICData?.idNumber : nationalIDorFile.text;
      req.isRegister = true;
    } else {
      req.patientIdentificationID = nationalIDorFile.text;
      req.nationalID = nationalIDorFile.text;
      req.deviceToken = null;
    }
    try {
      dynamic result;
      if (skipRegistration) {
        result = await authService.checkActivationCode(req.toJson(), value);
        if (result is Map) {
          final activation = CheckActivationCode.fromJson(result as Map<String, dynamic>);
          if (activation.errorCode == '699') {
            GifLoaderDialogUtils.hideDialog(context);
            onWrongActivationCode(activation.errorEndUserMessage.toString(), true);
          } else {
            await sharedPref.remove(FAMILY_FILE);
            activation.list!.isFamily = false;
            userdata = activation.list;
            await sharedPref.setString(BLOOD_TYPE, activation.patientBloodType ?? "");
            authenticatedUserObject.user = activation.list!;
            projectViewModel.setPrivilege(privilegeList: result);
            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, context);
            projectViewModel.analytics.loginRegistration.login_successful();
          }
        } else {
          GifLoaderDialogUtils.hideDialog(context);
          onWrongActivationCode(result.toString(), false);
          // context.showBottomSheet(
          //   child: ExceptionBottomSheet(
          //     message: result,
          //     showCancel: false,
          //     onOkPressed: () {
          //       Navigator.of(context).pop();
          //     },
          //   ),
          // );
          projectViewModel.analytics.loginRegistration.login_fail(error: result);
          projectViewModel.analytics.errorTracking.log('otp_verification_at_confirm_login', error: result);
        }
      } else {
        result = await authService.checkActivationCodeRegister(req.toJson(), value);
        if (result is Map) {
          final activation = CheckActivationCode.fromJson(result as Map<String, dynamic>);
          GifLoaderDialogUtils.hideDialog(context);
          Navigator.of(context).push(
            FadePage(page: RegisterNewStep2(nHICData, req)),
          );
          // Optionally: Navigator.popUntil(context, (route) => Utils.route(route, equalsTo: RegisterNew));
        } else {
          GifLoaderDialogUtils.hideDialog(context);
          onWrongActivationCode(result.toString(), false);
          // context.showBottomSheet(
          //   child: ExceptionBottomSheet(
          //     message: result,
          //     showCancel: false,
          //     onOkPressed: () {
          //       Navigator.of(context).pop();
          //     },
          //   ),
          // );
          // Optionally: log analytics here
        }
      }
    } catch (err) {
      GifLoaderDialogUtils.hideDialog(context);
      onWrongActivationCode(err.toString(), false);
      // context.showBottomSheet(
      //   child: ExceptionBottomSheet(
      //     message: err.toString(),
      //     showCancel: false,
      //     onOkPressed: () {
      //       Navigator.of(context).pop();
      //     },
      //   ),
      // );
    }
  }

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

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

    request.logInTokenID = 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 = int.parse(nationalIDorFile.text);
      request.patientIdentificationID = request.nationalID = "";
      request.searchType = 2;
    } else {
      request.patientID = 0;
      request.searchType = 1;
      request.patientIdentificationID = request.nationalID = nationalIDorFile != null ? nationalIDorFile.text : '0';
    }
    request.isRegister = false;

    request.deviceTypeID = request.searchType;
    return request;
  }

  startSMSService(type, skipRegistration) {
    late SMSOTP smsOtp;

    smsOtp = SMSOTP(
      context,
      type,
      mobileNo,
      (code) {
        checkActivationCode(
            value: code,
            type: type,
            skipRegistration: skipRegistration,
            onWrongActivationCode: (String? message, bool? isReroute) {
              if (isReroute == true) {
                context.showBottomSheet(
                  child: ExceptionBottomSheet(
                    message: message.toString(),
                    showCancel: false,
                    onOkPressed: () {
                      Navigator.popUntil(context, (route) => Utils.route(route, equalsTo: WelcomeLogin));
                    },
                  ),
                );
              } else {
                smsOtp.clearOTPInput();
                context.showBottomSheet(
                  child: ExceptionBottomSheet(
                    message: message.toString(),
                    onOkPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                );
              }
            });
      },
      () {
        smsOtp.dispose(); // Now we can reference it
        Navigator.pop(context);
      },
    );
    smsOtp.displayDialog(context);
  }

  checkActivationCodeMobile({value}) async {
    GifLoaderDialogUtils.showMyDialog(context);
    var request = this.getCommonRequest().toJson();
    var res;
    authService
        .checkActivationCode(request, value)
        .then((result) async => {
              res = result,
              if (result is Map)
                {
                  result = CheckActivationCode.fromJson(result as Map<String, dynamic>),
                  if (result.errorCode == '699')
                    {
                      GifLoaderDialogUtils.hideDialog(context),
                      context.showBottomSheet(
                        child: ExceptionBottomSheet(
                          message: result.errorEndUserMessage,
                          showCancel: false,
                          onOkPressed: () {
                            Navigator.popUntil(context, (route) => Utils.route(route, equalsTo: WelcomeLogin));
                          },
                        ),
                      ),
                    }
                  else
                    {
                      sharedPref.remove(FAMILY_FILE),
                      result.list.isFamily = false,
                      user = result.list,
                      sharedPref.setString(BLOOD_TYPE, result.patientBloodType ?? ""),
                      authenticatedUserObject.user = result.list,
                      context.read<ProjectViewModel>().setPrivilege(privilegeList: res),
                      await sharedPref.setObject(MAIN_USER, result.list),
                      await sharedPref.setObject(USER_PROFILE, result.list),
                      loginTokenID = result.logInTokenID,
                      await sharedPref.setObject(LOGIN_TOKEN_ID, result.logInTokenID),
                      await sharedPref.setString(TOKEN, result.authenticationTokenID),
                      checkIfUserAgreedBefore(result, context),
                      context.read<ProjectViewModel>().analytics.loginRegistration.login_successful(),
                    }
                }
              else
                {
                  GifLoaderDialogUtils.hideDialog(context),
                  context.showBottomSheet(
                    child: ExceptionBottomSheet(
                      message: result.errorEndUserMessage,
                      showCancel: false,
                      onOkPressed: () {
                        Navigator.of(context).pop();
                      },
                    ),
                  ),
                }
            })
        .catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      context.showBottomSheet(
        child: ExceptionBottomSheet(
          message: err,
          showCancel: false,
          onOkPressed: () {
            Navigator.of(context).pop();
          },
        ),
      );
    });
  }

  checkIfUserAgreedBefore(CheckActivationCode result, context) {
    if (projectViewModel.havePrivilege(109)) {
      authService.checkIfUserAgreed().then((result) {
        if (result['IsPatientAlreadyAgreed']) {
          goToHome(context);
        } else {
          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,
                showCancel: false,
                onOkPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            );
          });
        }
      }).catchError((err) {
        GifLoaderDialogUtils.hideDialog(context);
        context.showBottomSheet(
          child: ExceptionBottomSheet(
            message: err,
            showCancel: false,
            onOkPressed: () {
              Navigator.of(context).pop();
            },
          ),
        );
      });
    } else {
      goToHome(context);
    }
  }

  Future<void> goToHome(context) 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) {
      print(error);
    });
  }

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

  insertIMEI() {
    authService.insertDeviceImei(selectedOption).then((value) => {}).catchError((err) {
      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");

      ProjectViewModel projectViewModel = context.read<ProjectViewModel>();

      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);
      }
    });
  }
}
