import 'dart:convert';

import 'package:auto_size_text/auto_size_text.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/config/size_config.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' as checkActivation;
import 'package:hmg_patient_app/models/Authentication/check_paitent_authentication_req.dart';
import 'package:hmg_patient_app/models/Authentication/countries_list.dart';
import 'package:hmg_patient_app/models/Authentication/get_patient_occupation_list_response.dart';
import 'package:hmg_patient_app/models/Authentication/register_info_response.dart';
import 'package:hmg_patient_app/pages/BookAppointment/dialog/clinic_list_dialog.dart';
import 'package:hmg_patient_app/pages/insurance/insurance_update_screen.dart';
import 'package:hmg_patient_app/pages/landing/landing_page.dart';
import 'package:hmg_patient_app/pages/rateAppointment/rate_appointment_doctor.dart';
import 'package:hmg_patient_app/routes.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/uitl/app_shared_preferences.dart';
import 'package:hmg_patient_app/uitl/app_toast.dart';
import 'package:hmg_patient_app/uitl/date_uitl.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/buttons/defaultButton.dart';
import 'package:hmg_patient_app/widgets/dialogs/confirm_dialog.dart';
import 'package:hmg_patient_app/widgets/others/app_scaffold_widget.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:hijri/hijri_calendar.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';

class RegisterInfo extends StatefulWidget {
  final Function? changePageViewIndex;
  final int page;

  const RegisterInfo({Key? key, this.changePageViewIndex, this.page = 1}) : super(key: key);

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

class _RegisterInfo extends State<RegisterInfo> {
  final authService = new AuthProvider();
  final sharedPref = new AppSharedPreferences();
  RegisterInfoResponse registerInfo = RegisterInfoResponse();
  late bool isLoading;
  late int page;
  final List<Location> locationList = [
    new Location(name: 'KSA', value: '1', nameAr: "السعودية"),
    new Location(name: 'Dubai', value: '2', nameAr: "دبي"),
  ];
  String language = '1';
  late CheckPatientAuthenticationReq registerd_data;
  final List<Language> languageList = [
    new Language(name: 'English', value: '2', nameAr: "إنجليزي"),
    new Language(name: 'Arabic', value: '1', nameAr: "عربي"),
  ];
  final List<Language> genderList = [
    new Language(name: 'Male', value: 'M', nameAr: "ذكر"),
    new Language(name: 'Female', value: 'F', nameAr: "أنثى"),
  ];
  final List<Language> maritalList = [
    new Language(name: 'Married', value: 'M', nameAr: "متزوج"),
    new Language(name: 'Single', value: 'S', nameAr: "اعزب"),
    new Language(name: 'Divorce', value: 'D', nameAr: "الطلاق"),
  ];
  String email = '';
  List<CountriesLists> countriesList = [];
  late ToDoCountProviderModel toDoProvider;
  String location = '1';
  AuthenticatedUserObject authenticatedUserObject = locator<AuthenticatedUserObject>();

  late ProjectViewModel projectViewModel;

  AppointmentRateViewModel appointmentRateViewModel = locator<AppointmentRateViewModel>();
  bool isDubai = false;
  RegisterInfoResponse data = RegisterInfoResponse();
  late CheckPatientAuthenticationReq data2;
  String gender = 'M';
  String maritalStatus = 'M';
  String nationality = 'SAU';
  String selectedOccupationID = "";

  // List<GetPatientOccupationListResponse> patientOccupationList = [];
  // GetPatientOccupationListResponse? selectedPatientOccupation;

  final GlobalKey projectDropdownKey = GlobalKey();

  @override
  void initState() {
    if (widget.page == 1) {
      getCountries();
      // getPatientOccupationList();
    }
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      getRegisterInfo();
    });
    page = widget.page;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    toDoProvider = Provider.of<ToDoCountProviderModel>(context);
    return AppScaffold(
        appBarTitle: TranslationBase.of(context).register,
        isShowAppBar: false,
        isShowDecPage: false,
        body: SingleChildScrollView(
          padding: EdgeInsets.all(30),
          child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
            Row(
              children: [
                Expanded(
                  child: AppText(
                    TranslationBase.of(context).personalInfo,
                    fontSize: 16,
                    textAlign: TextAlign.left,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                Expanded(child: SizedBox())
              ],
            ),
            SizedBox(height: 10),
            (isDubai && page == 1)
                ? Column(
                    children: [
                      SizedBox(height: 20),
                      getnameField(TranslationBase.of(context).identificationNumber, registerd_data.patientIdentificationID, TranslationBase.of(context).mobileNumber,
                          registerd_data.patientMobileNumber.toString()),
                      // SizedBox(height: 20),
                      projectViewModel.isArabic
                          ? getnameField(
                              '',
                              inputWidget("First Name", "First Name English", 'fNameEn'),
                              '',
                              inputWidget("Last Name", "Last Name English", 'lNameEn'),
                            )
                          : SizedBox(
                              height: 0,
                            ),
                      getnameField(
                        '',
                        inputWidget(TranslationBase.of(context).firstName, TranslationBase.of(context).firstName, 'fName'),
                        '',
                        inputWidget(TranslationBase.of(context).middleName, TranslationBase.of(context).middleName, 'sName'),
                      ),

                      getnameField(
                        '',
                        inputWidget(TranslationBase.of(context).lastName, TranslationBase.of(context).lastName, 'lName'),
                        TranslationBase.of(context).gender,
                        Container(
                            height: 20,
                            child: DropdownButtonHideUnderline(
                                child: DropdownButton(
                                    isExpanded: true,
                                    value: gender,
                                    hint: Text(TranslationBase.of(context).gender),
                                    iconSize: 40,
                                    elevation: 16,
                                    onChanged: (value) => {
                                          setState(() {
                                            gender = value!;
                                            registerInfo.gender = value;
                                          })
                                        },
                                    items: genderList.map<DropdownMenuItem<String>>((Language value) {
                                      return DropdownMenuItem<String>(
                                        value: value.value,
                                        child: Text(
                                          projectViewModel.isArabic == 1 ? value.nameAr! : value.name!,
                                        ),
                                      );
                                    }).toList()))),
                      ),
                      SizedBox(height: 20),
                      getnameField(
                          TranslationBase.of(context).maritalStatus,
                          Container(
                              height: 18,
                              child: DropdownButtonHideUnderline(
                                  child: DropdownButton(
                                      isExpanded: true,
                                      value: maritalStatus,
                                      hint: Text(TranslationBase.of(context).maritalStatus),
                                      iconSize: 40,
                                      elevation: 16,
                                      onChanged: (value) => {
                                            setState(() {
                                              maritalStatus = value!;
                                              registerInfo.maritalStatusCode = value;
                                            })
                                          },
                                      items: maritalList.map<DropdownMenuItem<String>>((Language value) {
                                        return DropdownMenuItem<String>(
                                          value: value.value,
                                          child: Text(
                                            projectViewModel.isArabic == 1 ? value.nameAr! : value.name!,
                                          ),
                                        );
                                      }).toList()))),
                          TranslationBase.of(context).nationality,
                          Container(
                              height: 22,
                              child: DropdownButtonHideUnderline(
                                  child: DropdownButton(
                                      isExpanded: true,
                                      value: nationality,
                                      hint: Text(TranslationBase.of(context).nationality),
                                      iconSize: 40,
                                      elevation: 16,
                                      onChanged: (value) => {
                                            setState(() {
                                              nationality = value!;
                                              registerInfo.nationalityCode = value;
                                            })
                                          },
                                      items: countriesList.map<DropdownMenuItem<String>>((CountriesLists value) {
                                        return DropdownMenuItem<String>(
                                          value: value.iD,
                                          child: Text(
                                            value.name!,
                                          ),
                                        );
                                      }).toList())))),
                      SizedBox(height: 20),
                      getnameField(TranslationBase.of(context).dateOfBirth, registerd_data.dob, "", ""),
                      SizedBox(height: 20),
                    ],
                  )
                : (registerInfo.healthId != null && page == 1)
                    ? Column(
                        children: [
                          SizedBox(height: 10),
                          getnameField(TranslationBase.of(context).identificationNumber, registerInfo.idNumber, TranslationBase.of(context).firstName,
                              registerInfo.firstNameEn == '-' ? registerInfo.firstNameAr : registerInfo.firstNameEn),
                          SizedBox(height: 10),
                          getnameField(TranslationBase.of(context).middleName, registerInfo.secondNameEn == '-' ? registerInfo.secondNameEn : registerInfo.secondNameEn,
                              TranslationBase.of(context).lastName, registerInfo.lastNameEn == '-' ? registerInfo.lastNameEn : registerInfo.lastNameEn),
                          SizedBox(height: 10),
                          getnameField(
                              TranslationBase.of(context).gender,
                              registerInfo.maritalStatusCode == 'U'
                                  ? 'Unknown'
                                  : registerInfo.maritalStatusCode == 'M'
                                      ? 'Male'
                                      : 'Female',
                              TranslationBase.of(context).maritalStatus,
                              registerInfo.maritalStatus),
                          SizedBox(height: 10),
                          getnameField(TranslationBase.of(context).nationality, registerInfo.nationality, TranslationBase.of(context).mobileNumber, registerd_data.patientMobileNumber.toString()),
                          SizedBox(height: 10),
                          getnameField(TranslationBase.of(context).dateOfBirth, registerInfo.dateOfBirth, "", ""),
                        ],
                      )
                    : widget.page == 2
                        ? Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              // (!isDubai)
                              //     ? Container(
                              //         width: double.infinity,
                              //         decoration: containerRadius(Colors.white, 12),
                              //         padding: EdgeInsets.only(left: 10, right: 10, top: 12, bottom: 12),
                              //         child: Row(
                              //           children: [
                              //             Flexible(
                              //               child: Column(
                              //                 crossAxisAlignment: CrossAxisAlignment.start,
                              //                 children: [
                              //                   Text(
                              //                     TranslationBase.of(context).selectOccupation,
                              //                     style: TextStyle(
                              //                       fontSize: 11,
                              //                       letterSpacing: -0.44,
                              //                       fontWeight: FontWeight.w600,
                              //                     ),
                              //                   ),
                              //                   Container(
                              //                     height: 18,
                              //                     width: double.infinity,
                              //                     child: DropdownButtonHideUnderline(
                              //                       child: DropdownButton<GetPatientOccupationListResponse>(
                              //                         key: projectDropdownKey,
                              //                         hint: Text(TranslationBase.of(context).selectOccupation),
                              //                         value: selectedPatientOccupation,
                              //                         iconSize: 0,
                              //                         isExpanded: true,
                              //                         style: TextStyle(fontSize: 14, letterSpacing: -0.56, color: Colors.black),
                              //                         items: patientOccupationList.map((GetPatientOccupationListResponse item) {
                              //                           return DropdownMenuItem<GetPatientOccupationListResponse>(
                              //                             value: item,
                              //                             child: AutoSizeText(
                              //                               projectViewModel.isArabic ? item.descriptionN! : item.description!,
                              //                               maxLines: 1,
                              //                               minFontSize: 10,
                              //                               style: TextStyle(
                              //                                 fontSize: SizeConfig.textMultiplier! * 1.6,
                              //                                 fontWeight: FontWeight.w600,
                              //                                 letterSpacing: -0.39,
                              //                                 height: 0.8,
                              //                               ),
                              //                             ),
                              //                             // Text('${item.name!}'),
                              //                           );
                              //                         }).toList(),
                              //                         onChanged: (GetPatientOccupationListResponse? newValue) {
                              //                           setState(() {
                              //                             selectedPatientOccupation = newValue!;
                              //                             selectedOccupationID = selectedPatientOccupation!.occupationID!;
                              //                             registerInfo.occupationID = selectedOccupationID;
                              //                           });
                              //                           debugPrint("Selected Occupation ID: ${registerInfo.occupationID}");
                              //                         },
                              //                       ),
                              //                     ),
                              //                   ),
                              //                 ],
                              //               ),
                              //             ),
                              //             Icon(Icons.keyboard_arrow_down),
                              //           ],
                              //         ))
                              //     : SizedBox(),
                              mHeight(20),
                              Container(
                                  width: double.infinity,
                                  decoration: containerRadius(Colors.white, 12),
                                  padding: EdgeInsets.only(left: 10, right: 10, top: 5, bottom: 25),
                                  child: Row(children: [
                                    Flexible(
                                        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                                      Text(
                                        TranslationBase.of(context).prefferedLanguage,
                                        style: TextStyle(
                                          fontSize: 11,
                                          letterSpacing: -0.44,
                                          fontWeight: FontWeight.w600,
                                        ),
                                      ),
                                      Container(
                                          height: 18,
                                          child: DropdownButtonHideUnderline(
                                              child: DropdownButton(
                                                  isExpanded: true,
                                                  value: language,
                                                  hint: Text(TranslationBase.of(context).prefferedLanguage),
                                                  iconSize: 40,
                                                  elevation: 16,
                                                  onChanged: (value) => {
                                                        setState(() {
                                                          language = value!;
                                                        })
                                                      },
                                                  items: languageList.map<DropdownMenuItem<String>>((Language value) {
                                                    return DropdownMenuItem<String>(
                                                      value: value.value,
                                                      child: Text(
                                                        projectViewModel.isArabic == 1 ? value.nameAr! : value.name!,
                                                      ),
                                                    );
                                                  }).toList())))
                                    ]))
                                  ])),
                              SizedBox(
                                height: 20,
                              ),
                              Container(
                                  width: double.infinity,
                                  decoration: containerRadius(Colors.white, 12),
                                  padding: EdgeInsets.only(left: 10, right: 10, top: 5, bottom: 25),
                                  child: Row(children: [
                                    Flexible(
                                        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                                      Text(
                                        TranslationBase.of(context).selectLocation,
                                        style: TextStyle(
                                          fontSize: 11,
                                          letterSpacing: -0.44,
                                          fontWeight: FontWeight.w600,
                                        ),
                                      ),
                                      Container(
                                          height: 18,
                                          child: DropdownButtonHideUnderline(
                                              child: DropdownButton(
                                                  isExpanded: true,
                                                  value: location,
                                                  hint: Text(TranslationBase.of(context).selectLocation),
                                                  iconSize: 40,
                                                  elevation: 16,
                                                  onChanged: (value) => {
                                                        setState(() {
                                                          location = value!;
                                                        })
                                                      },
                                                  items: locationList.map<DropdownMenuItem<String>>((Location value) {
                                                    return DropdownMenuItem<String>(
                                                      value: value.value,
                                                      child: Text(
                                                        projectViewModel.isArabic == 1 ? value.nameAr! : value.name!,
                                                      ),
                                                    );
                                                  }).toList())))
                                    ]))
                                  ])),
                              SizedBox(
                                height: 20,
                              ),
                              Container(
                                  width: double.infinity,
                                  decoration: containerRadius(Colors.white, 12),
                                  padding: EdgeInsets.only(left: 10, right: 10, top: 5, bottom: 12),
                                  margin: EdgeInsets.only(bottom: 0),
                                  child: Row(children: [
                                    Flexible(
                                        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                                      Text(
                                        TranslationBase.of(context).email,
                                        style: TextStyle(
                                          fontSize: 11,
                                          letterSpacing: -0.44,
                                          fontWeight: FontWeight.w600,
                                        ),
                                      ),
                                      Container(
                                          child: TextField(
                                        keyboardType: TextInputType.emailAddress,
                                        onChanged: (value) {
                                          setState(() {
                                            email = value;
                                          });
                                        },
                                        style: TextStyle(
                                          fontSize: 14,
                                          height: 21 / 14,
                                          fontWeight: FontWeight.w400,
                                          color: Color(0xff2B353E),
                                          letterSpacing: -0.44,
                                        ),
                                        decoration: InputDecoration(
                                          isDense: true,
                                          hintStyle: TextStyle(
                                            fontSize: 14,
                                            height: 21 / 14,
                                            fontWeight: FontWeight.w400,
                                            color: Color(0xff575757),
                                            letterSpacing: -0.56,
                                          ),
                                          prefixIconConstraints: BoxConstraints(minWidth: 50),
                                          contentPadding: EdgeInsets.zero,
                                          border: InputBorder.none,
                                          focusedBorder: InputBorder.none,
                                          enabledBorder: InputBorder.none,
                                        ),
                                      ))
                                    ]))
                                  ])),
                            ],
                          )
                        : SizedBox(),
          ]),
        ),
        bottomSheet: Container(
            width: double.maxFinite,
            height: 80.0,
            child: Row(
              children: [
                Expanded(
                  child: Padding(
                      padding: EdgeInsets.all(10),
                      child: DefaultButton(TranslationBase.of(context).cancel, () {
                        Navigator.of(context).pop();
                        // widget.changePageViewIndex!(0);
                        // getPatientOccupationList();
                        locator<GAnalytics>().loginRegistration.registration_cancel(step: page == 1 ? 'personal info' : 'other details');
                      }, textColor: Colors.white, color: Color(0xffD02127))),
                ),
                Expanded(
                  child: Padding(
                      padding: EdgeInsets.all(10),
                      child: DefaultButton(page == 1 ? TranslationBase.of(context).next : TranslationBase.of(context).register, () {
                        nextPage();
                        page == 1 ? locator<GAnalytics>().loginRegistration.registration_personal_info() : locator<GAnalytics>().loginRegistration.registration_patient_info();
                      }, textColor: Colors.white, color: isValid() == true ? Color(0xff359846) : Colors.grey)),
                ),
              ],
            )));
  }

  nextPage() async {
    if (page == 1) {
      if (isDubai) {
        await setRegisterData();
        widget.changePageViewIndex!(2);
      } else {
        widget.changePageViewIndex!(2);
      }
    } else {
      registerNow();

      // if (isDubai) {
      //   registerNow();
      // } else {
      //   if (selectedPatientOccupation != null) {
      //     registerNow();
      //   } else {
      //     AppToast.showErrorToast(message: TranslationBase.of(context).selectOccupationError);
      //   }
      // }
    }
  }

  setRegisterData() async {
    registerInfo.gender = gender;
    registerInfo.maritalStatusCode = maritalStatus;
    registerInfo.nationalityCode = nationality;
    projectViewModel.setRegisterData(registerInfo);
    // await sharedPref.setObject(REGISTER_INFO_DUBAI, registerInfo);
  }

  registerNow() {
    dynamic request;

    if (isDubai)
      request = getTempUserRequestDubai();
    else
      request = getTempUserRequest();

    print(request);

    GifLoaderDialogUtils.showMyDialog(context, barrierDismissible: true);
    dynamic res;
    this
        .authService
        .registerUser(request)
        .then((result) async => {
              if (result is String)
                {
                  GifLoaderDialogUtils.hideDialog(context),
                  new ConfirmDialog(
                      context: context,
                      confirmMessage: result,
                      okText: TranslationBase.of(context).ok,
                      cancelText: TranslationBase.of(context).cancel_nocaps,
                      okFunction: () => {ConfirmDialog.closeAlertDialog(context)},
                      cancelFunction: () => {ConfirmDialog.closeAlertDialog(context)}).showAlertDialog(context)
                }
              else
                {
                  res = result,
                  result = checkActivation.CheckActivationCode.fromJson(result),
                  // result.list.isFamily = false,
                  // sharedPref.setObject(USER_PROFILE, result.list),
                  // this.sharedPref.setObject(MAIN_USER, result.list),
                  // sharedPref.setObject(LOGIN_TOKEN_ID, result.logInTokenID),
                  // sharedPref.setString(TOKEN, result.authenticationTokenID),
                  // this.setUser(result),
                  sharedPref.remove(FAMILY_FILE),
                  result.list.isFamily = false,

                  await sharedPref.setString(BLOOD_TYPE, result.patientBloodType ?? ""),
                  authenticatedUserObject.user = result.list,
                  projectViewModel.setPrivilege(privilegeList: res),
                  await sharedPref.setObject(MAIN_USER, result.list),
                  await sharedPref.setObject(USER_PROFILE, result.list),

                  await sharedPref.setObject(LOGIN_TOKEN_ID, result.logInTokenID),
                  await sharedPref.setString(TOKEN, result.authenticationTokenID),
                  AppToast.showSuccessToast(message: TranslationBase.of(context).successRegister),
                  checkIfUserAgreedBefore(result),
                  projectViewModel.analytics.loginRegistration.registration_confirmation()
                }
            })
        .catchError((err) {
      // GifLoaderDialogUtils.hideDialog(context);
      ConfirmDialog dialog = new ConfirmDialog(
          context: context,
          confirmMessage: err,
          okText: TranslationBase.of(context).confirm,
          cancelText: TranslationBase.of(context).cancel_nocaps,
          okFunction: () => {ConfirmDialog.closeAlertDialog(context)},
          cancelFunction: () => {ConfirmDialog.closeAlertDialog(context)});
      dialog.showAlertDialog(context);
      projectViewModel.analytics.loginRegistration.registration_fail(errorType: "");
    });
  }

  setUser(result) async {
    await authenticatedUserObject.getUser(getUser: true);
    authenticatedUserObject.isLogin = true;
    appointmentRateViewModel.isLogin = true;
    projectViewModel.isLogin = true;
    authenticatedUserObject.user = result.list;
    Navigator.of(context).pushNamed(HOME);
  }

  getRegisterInfo() async {
    if (await sharedPref.getObject(NHIC_DATA) != null) {
      data = RegisterInfoResponse.fromJson(await sharedPref.getObject(NHIC_DATA));
      this.registerInfo = data;
    }
    if (await sharedPref.getObject(REGISTER_DATA_FOR_LOGIIN) != null) {
      data2 = CheckPatientAuthenticationReq.fromJson(await sharedPref.getObject(REGISTER_DATA_FOR_LOGIIN));

      setState(() {
        this.registerd_data = data2;
        isDubai = data2.patientOutSA == 1 ? true : false;
        if (isDubai) location = '2';
      });
    }

    // try {
    //   var patientOccupationListVal = json.decode(await sharedPref.getString(PATIENT_OCCUPATION_LIST));
    //   patientOccupationListVal.forEach((v) {
    //     patientOccupationList.add(new GetPatientOccupationListResponse.fromJson(v));
    //   });
    //   setState(() {});
    // } catch (ex) {
    //   print(ex.toString());
    // }
  }

  getTempUserRequest() {
    DateFormat dateFormat = DateFormat("mm/dd/yyyy");
    print(dateFormat.parse(registerInfo.dateOfBirth!));
    var hDate = new HijriCalendar.fromDate(dateFormat.parse(registerInfo.dateOfBirth!));
    var date = hDate.toString();
    return {
      "Patientobject": {
        "TempValue": true,
        "PatientIdentificationType": registerInfo.idNumber!.substring(0, 1) == "1" ? 1 : 2,
        "PatientIdentificationNo": registerInfo.idNumber,
        "MobileNumber": registerd_data.patientMobileNumber,
        "PatientOutSA": (registerd_data.zipCode == '966' || registerd_data.zipCode == '+966') ? 0 : 1,
        "FirstNameN": registerInfo.firstNameAr,
        "FirstName": registerInfo.firstNameEn,
        "MiddleNameN": registerInfo.secondNameAr,
        "MiddleName": registerInfo.secondNameEn,
        "LastNameN": registerInfo.lastNameAr,
        "LastName": registerInfo.lastNameEn,
        "StrDateofBirth": registerInfo.dateOfBirth,
        "DateofBirth": DateUtil.convertISODateToJsonDate(registerInfo.dateOfBirth!.replaceAll('/', '-')),
        "Gender": registerInfo.gender == 'M' ? 1 : 2,
        "NationalityID": registerInfo.nationalityCode,
        "eHealthIDField": registerInfo.healthId,
        "DateofBirthN": date,
        "EmailAddress": email,
        "SourceType": location,
        "PreferredLanguage": registerd_data.languageID.toString(),
        // "OccupationID": registerInfo.occupationID,
        "Marital": registerInfo.maritalStatusCode == 'U'
            ? '0'
            : registerInfo.maritalStatusCode == 'M'
                ? '1'
                : '2',
      },
      "PatientIdentificationID": registerInfo.idNumber,
      "PatientMobileNumber": registerd_data.patientMobileNumber.toString()[0] == '0' ? registerd_data.patientMobileNumber : '0' + registerd_data.patientMobileNumber.toString(),
    };
  }

  getTempUserRequestDubai() {
    DateFormat dateFormat = DateFormat("mm/dd/yyyy");
    registerInfo = projectViewModel.registerInfo;
    print(dateFormat.parse(registerd_data.dob!));
    var hDate = new HijriCalendar.fromDate(dateFormat.parse(registerd_data.dob!));
    var date = hDate.toString();
    final DateFormat dateFormat1 = DateFormat('MM/dd/yyyy');
    final DateFormat dateFormat2 = DateFormat('dd/MM/yyyy');

    return {
      "Patientobject": {
        "TempValue": true,
        "PatientIdentificationType": registerd_data.patientIdentificationID!.substring(0, 1) == "1" ? 1 : 2,
        "PatientIdentificationNo": registerd_data.patientIdentificationID,
        "MobileNumber": registerd_data.patientMobileNumber,
        "PatientOutSA": (registerd_data.zipCode == '966' || registerd_data.zipCode == '+966') ? 0 : 1,
        "FirstNameN": registerInfo.firstNameAr ?? "",
        "FirstName": registerInfo.firstNameEn ?? "",
        "MiddleNameN": registerInfo.secondNameAr ?? ".",
        "MiddleName": registerInfo.secondNameEn ?? ".",
        "LastNameN": registerInfo.lastNameAr ?? "",
        "LastName": registerInfo.lastNameEn ?? "",
        "StrDateofBirth": dateFormat1.format(dateFormat2.parse(registerd_data.dob!)),
        "DateofBirth": DateUtil.convertISODateToJsonDate(registerd_data.dob!.replaceAll('/', '-')),
        "Gender": registerInfo.gender == 'M' ? 1 : 2,
        "NationalityID": registerInfo.nationalityCode,
        "eHealthIDField": null,
        "DateofBirthN": date,
        "EmailAddress": email,
        "SourceType": location,
        "PreferredLanguage": registerd_data.languageID.toString(),
        "Marital": registerInfo.maritalStatusCode == 'U'
            ? '0'
            : registerInfo.maritalStatusCode == 'M'
                ? '1'
                : '2',
      },
      "PatientIdentificationID": registerd_data.patientIdentificationID,
      "PatientMobileNumber": registerd_data.patientMobileNumber.toString()[0] == '0' ? registerd_data.patientMobileNumber : '0' + registerd_data.patientMobileNumber.toString(),
      "DOB": registerd_data.dob,
      "IsHijri": registerd_data.isHijri
    };
  }

  bool isValid() {
    if ((location != null && language != null && Utils.validEmail(email) == true) ||
        (registerInfo.firstNameEn != null && registerInfo.lastNameEn != null) ||
        (projectViewModel.isArabic && registerInfo.firstNameEn != null && registerInfo.firstNameAr != null && registerInfo.lastNameEn != null && registerInfo.lastNameAr != null)) {
      return true;
    } else {
      return false;
    }
  }

  Widget getnameField(name1, value1, name2, value2) {
    return Row(
      children: [
        Expanded(
            child: Padding(
                padding: EdgeInsets.only(left: 5, right: 5),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      name1,
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                        letterSpacing: -0.44,
                      ),
                    ),
                    value1 is String
                        ? Text(
                            value1,
                            style: TextStyle(
                              fontSize: 12,
                              fontWeight: FontWeight.w600,
                              letterSpacing: -0.44,
                            ),
                          )
                        : value1,
                  ],
                ))),
        Expanded(
            child: Padding(
                padding: EdgeInsets.only(left: 5, right: 5),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      name2,
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                        letterSpacing: -0.44,
                      ),
                    ),
                    value2 is String
                        ? Text(
                            value2,
                            style: TextStyle(
                              fontSize: 12,
                              fontWeight: FontWeight.w600,
                              letterSpacing: -0.44,
                            ),
                          )
                        : value2,
                  ],
                )))
      ],
    );
  }

  checkIfUserAgreedBefore(checkActivation.CheckActivationCode result) {
    if (result.isNeedUserAgreement == true) {
      //TODO need to implement agreement page here
      insertIMEI();
    } else {
      insertIMEI();
    }
  }

  insertIMEI() async {
    var selectedOption = await sharedPref.getInt(LAST_LOGIN);
    authService.insertDeviceImei(selectedOption).then((value) => {goToHome()}).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
    });
  }

  goToHome() async {
    authenticatedUserObject.isLogin = true;
    appointmentRateViewModel.isLogin = true;
    projectViewModel.isLogin = true;
    projectViewModel.user = authenticatedUserObject.user;
    await authenticatedUserObject.getUser(getUser: true);
    getToDoCount();
    GifLoaderDialogUtils.hideDialog(AppGlobal.context);
    ConfirmDialog dialog = new ConfirmDialog(
        context: context,
        confirmMessage: TranslationBase.of(context).validInsurance,
        okText: TranslationBase.of(context).yes,
        cancelText: TranslationBase.of(context).no,
        okFunction: () {
          ConfirmDialog.closeAlertDialog(context);
          Navigator.pushAndRemoveUntil(
            context,
            MaterialPageRoute(builder: (context) => LandingPage()),
            (Route<dynamic> route) => false,
          );
          Navigator.push(context, FadePage(page: InsuranceUpdate()));
        },
        cancelFunction: () {
          Navigator.pushAndRemoveUntil(
            context,
            MaterialPageRoute(builder: (context) => LandingPage()),
            (Route<dynamic> route) => false,
          );
        });
    dialog.showAlertDialog(context);

    // int languageID = Provider.of<ProjectViewModel>(context, listen: false).isArabic ? 1 : 2;
    // appointmentRateViewModel.getIsLastAppointmentRatedList(languageID).then((value) {
    //   getToDoCount();
    //   GifLoaderDialogUtils.hideDialog(AppGlobal.context);
    //   if (appointmentRateViewModel.isHaveAppointmentNotRate) {
    //     Navigator.pushAndRemoveUntil(
    //         context,
    //         FadePage(
    //           page: RateAppointmentDoctor(isFromRegistration: true),
    //         ),
    //         (r) => false);
    //   } else {
    //     ConfirmDialog dialog = new ConfirmDialog(
    //         context: context,
    //         confirmMessage: TranslationBase.of(context).validInsurance,
    //         okText: TranslationBase.of(context).yes,
    //         cancelText: TranslationBase.of(context).no,
    //         okFunction: () {
    //           ConfirmDialog.closeAlertDialog(context);
    //           Navigator.pushAndRemoveUntil(
    //             context,
    //             MaterialPageRoute(builder: (context) => LandingPage()),
    //             (Route<dynamic> route) => false,
    //           );
    //           Navigator.push(context, FadePage(page: InsuranceUpdate()));
    //         },
    //         cancelFunction: () {
    //           Navigator.pushAndRemoveUntil(
    //             context,
    //             MaterialPageRoute(builder: (context) => LandingPage()),
    //             (Route<dynamic> route) => false,
    //           );
    //         });
    //     dialog.showAlertDialog(context);
    //   }
    // }).catchError((err) {
    //   print(err);
    //   //GifLoaderDialogUtils.hideDialog(context);
    // });
    // SMSOTP.showLoadingDialog(context, false),
  }

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

  getCountries() {
    ClinicListService service = new ClinicListService();
    service.getCountries().then((res) {
      if (res['MessageStatus'] == 1) {
        res['ListNationality'].forEach((items) => {countriesList.add(CountriesLists.fromJson(items))});

        setState(() {});
      }
    }).catchError((err) {
      print(err);
    });
  }

  Widget inputWidget(String _labelText, String _hintText, String name, {String? prefix, bool isEnable = true, bool hasSelection = false}) {
    return Container(
      padding: EdgeInsets.only(left: 10, right: 10, bottom: 5, top: 5),
      alignment: Alignment.center,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(15),
        color: Colors.white,
        border: Border.all(
          color: Color(0xffefefef),
          width: 1,
        ),
      ),
      child: InkWell(
        onTap: hasSelection ? () {} : null,
        child: Row(
          children: [
            Expanded(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    _labelText,
                    style: TextStyle(
                      fontSize: 11,
                      fontWeight: FontWeight.w600,
                      color: Color(0xff2B353E),
                      letterSpacing: -0.44,
                    ),
                  ),
                  TextField(
                    enabled: isEnable,
                    scrollPadding: EdgeInsets.zero,
                    keyboardType: TextInputType.text,
                    // controller: _controller,
                    onChanged: (value) => {
                      setState(() {
                        switch (name) {
                          case 'fName':
                            {
                              if (projectViewModel.isArabic) {
                                registerInfo.firstNameAr = value;
                              } else {
                                registerInfo.firstNameEn = value;
                                registerInfo.firstNameAr = '...';
                              }
                            }
                            break;
                          case 'sName':
                            {
                              if (projectViewModel.isArabic) {
                                registerInfo.secondNameAr = value.isEmpty ? "." : value;
                                registerInfo.secondNameEn = '...';
                              } else {
                                registerInfo.secondNameEn = value.isEmpty ? "." : value;
                                registerInfo.secondNameAr = '...';
                              }
                            }
                            break;
                          case 'lName':
                            {
                              if (projectViewModel.isArabic) {
                                registerInfo.lastNameAr = value;
                              } else {
                                registerInfo.lastNameEn = value;
                                registerInfo.lastNameAr = '...';
                              }
                            }
                            break;
                          case 'fNameEn':
                            registerInfo.firstNameEn = value;
                            break;
                          case 'lNameEn':
                            registerInfo.lastNameEn = value;
                            break;
                        }
                      })
                      //_controller.text =value
                    },
                    style: TextStyle(
                      fontSize: 14,
                      height: 21 / 14,
                      fontWeight: FontWeight.w400,
                      color: Color(0xff2B353E),
                      letterSpacing: -0.44,
                    ),
                    decoration: InputDecoration(
                      isDense: true,
                      hintText: _hintText,
                      hintStyle: TextStyle(
                        fontSize: 14,
                        height: 21 / 14,
                        fontWeight: FontWeight.w400,
                        color: Color(0xff575757),
                        letterSpacing: -0.56,
                      ),
                      prefixIconConstraints: BoxConstraints(minWidth: 50),
                      contentPadding: EdgeInsets.zero,
                      border: InputBorder.none,
                      focusedBorder: InputBorder.none,
                      enabledBorder: InputBorder.none,
                    ),
                  ),
                ],
              ),
            ),
            if (hasSelection) Icon(Icons.keyboard_arrow_down_outlined),
          ],
        ),
      ),
    );
  }

  void openDropdown(GlobalKey key) {
    GestureDetector? detector;
    void searchForGestureDetector(BuildContext element) {
      element.visitChildElements((element) {
        if (element.widget != null && element.widget is GestureDetector) {
          detector = element.widget as GestureDetector?;
          // return false;
        } else {
          searchForGestureDetector(element);
        }
        // return true;
      });
    }

    searchForGestureDetector(key.currentContext!);
    assert(detector != null);
    detector!.onTap!();
  }
}

class Language {
  final String? name;
  final String? value;
  final String? nameAr;

  Language({this.name, this.value, this.nameAr});
}

class Location {
  final String? name;
  final String? value;
  final String? nameAr;

  Location({this.name, this.value, this.nameAr});
}
