import 'dart:convert';
import 'dart:core';
import 'dart:typed_data';

import 'package:badges/badges.dart';
import 'package:connectivity/connectivity.dart';
import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.dart';
import 'package:diplomaticquarterapp/pages/Blood/my_balance_page.dart';
import 'package:diplomaticquarterapp/pages/MyAppointments/MyAppointments.dart';
import 'package:diplomaticquarterapp/pages/insurance/insurance_approval_screen.dart';
import 'package:diplomaticquarterapp/pages/insurance/insurance_card_screen.dart';
import 'package:diplomaticquarterapp/pages/insurance/insurance_update_screen.dart';
import 'package:diplomaticquarterapp/pages/medical/active_medications/ActiveMedicationsPage.dart';
import 'package:diplomaticquarterapp/pages/medical/allergies_page.dart';
import 'package:diplomaticquarterapp/pages/medical/ask_doctor/ask_doctor_home_page.dart';
import 'package:diplomaticquarterapp/pages/medical/doctor/doctor_home_page.dart';
import 'package:diplomaticquarterapp/pages/medical/eye/EyeMeasurementsPage.dart';
import 'package:diplomaticquarterapp/pages/medical/labs/labs_home_page.dart';
import 'package:diplomaticquarterapp/pages/medical/medical_profile_page.dart';
import 'package:diplomaticquarterapp/pages/medical/my_trackers/my_trackers.dart';
import 'package:diplomaticquarterapp/pages/medical/patient_sick_leave_page.dart';
import 'package:diplomaticquarterapp/pages/medical/prescriptions/prescriptions_home_page.dart';
import 'package:diplomaticquarterapp/pages/medical/radiology/radiology_home_page.dart';
import 'package:diplomaticquarterapp/pages/medical/reports/monthly_reports.dart';
import 'package:diplomaticquarterapp/pages/medical/reports/report_home_page.dart';
import 'package:diplomaticquarterapp/pages/medical/smart_watch_health_data/smart_watch_instructions.dart';
import 'package:diplomaticquarterapp/pages/medical/vital_sign/vital_sign_details_screen.dart';
import 'package:diplomaticquarterapp/pages/vaccine/my_vaccines_screen.dart';
import 'package:diplomaticquarterapp/services/authentication/auth_provider.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/data_display/medical/medical_profile_item.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/alert_dialog.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../Constants.dart';
import 'app_shared_preferences.dart';
import 'app_toast.dart';
import 'gif_loader_dialog_utils.dart';

AppSharedPreferences sharedPref = new AppSharedPreferences();

class Utils {
  // static ProgressDialog pr;

  ///show  custom Error Toast
  ///  [message] to show for user
  static showErrorToast([String message]) {
    String localMsg = generateContactAdminMessage();
    if (message != null) {
      localMsg = message.toString();
    }
    AppToast.showErrorToast(message: localMsg);
  }

  /// Check The Internet Connection
  static Future<bool> checkConnection() async {
    ConnectivityResult connectivityResult =
        await (Connectivity().checkConnectivity());
    if ((connectivityResult == ConnectivityResult.mobile) ||
        (connectivityResult == ConnectivityResult.wifi)) {
      return true;
    } else {
      return false;
    }
  }

  /// generate Contact Admin Message
  static generateContactAdminMessage([err]) {
    String localMsg = 'Something wrong happened, please contact the admin';
    if (err != null) {
      localMsg = localMsg + '\n \n' + err.toString();
    }
    return localMsg;
  }

  /// hides the keyboard if its already open
  static hideKeyboard(BuildContext context) {
    FocusScope.of(context).unfocus();
  }

  bool isSAUDIIDValid(String id, type) {
    if (type == 1) {
      if (id == null) {
        return false;
      }
      try {
        id = id.toString();
        id = id.trim();
        var returnValue = int.parse(id);
        var sum = 0;
        if (returnValue > 0) {
          var type = int.parse(id[0]);

          if (id.length != 10) {
            return false;
          }
          if (type != 2 && type != 1) {
            return false;
          }

          for (var i = 0; i < 10; i++) {
            if (i % 2 == 0) {
              var a = id[i];
              var x = int.parse(a) * 2;
              var b = x.toString();
              if (b.length == 1) {
                b = "0" + b;
              }
              sum += int.parse(b[0]) + int.parse(b[1]);
            } else {
              sum += int.parse(id[i]);
            }
          }
          return sum % 10 == 0;
        }
      } catch (err) {}
      return false;
    } else {
      return true;
    }
  }

  static String getAppointmentTransID(int projectID, int clinicID, int appoNo) {
    return projectID.toString() +
        '-' +
        clinicID.toString() +
        '-' +
        appoNo.toString();
  }

  static String getAdvancePaymentTransID(int projectID, int fileNumber) {
    return projectID.toString() +
        '-' +
        fileNumber.toString() +
        '-' +
        DateTime.now().millisecondsSinceEpoch.toString();
  }

  bool validateIDBox(String value, type) {
    Pattern pattern = loginIDPattern(type); //r'^\d+(?:\.\d+)?$';

    RegExp regex = new RegExp(pattern);
    return regex.hasMatch(value);
  }

  String loginIDPattern(loginType) {
    var length = loginType == 1 ? 10 : 7;
    return "([0-9]{" + length.toString() + "})";
  }

  static showProgressDialog(context, [String message = "Loading..."]) async {
    // pr = ProgressDialog(context,
    //     type: ProgressDialogType.Normal, isDismissible: false, showLogs: false);
    // pr.style(
    //     message: message,
    //     borderRadius: 10.0,
    //     backgroundColor: Colors.white,
    //     elevation: 10.0,
    //     insetAnimCurve: Curves.easeInOut,
    //     progress: 0.0,
    //     maxProgress: 100.0,
    //     progressTextStyle: TextStyle(
    //         color: Colors.black, fontSize: 13.0, fontWeight: FontWeight.w400),
    //     messageTextStyle: TextStyle(
    //         color: Colors.black, fontSize: 19.0, fontWeight: FontWeight.w600));

    // if (!pr.isShowing()) {
    //   await pr.show();
    // } else {
    //   await pr.hide();
    //   await pr.show();
    // }
  }

  static hideProgressDialog() async {
    // if (pr.isShowing()) {
    //   await pr.hide();
    // }
  }

  static getPhoneNumberWithoutZero(String number){
    String newNumber="";
    if(number.startsWith('0'))
    {
      newNumber = number.substring(1);
    }
    return newNumber;
  }

  static Uint8List dataFromBase64String(String base64String) {
    return base64Decode(base64String);
  }

  static validEmail(email) {
    return RegExp(
            r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+")
        .hasMatch(email);
  }

  static List<Widget> myMedicalList({ProjectViewModel projectViewModel, BuildContext context, bool isLogin, count}) {
    List<Widget> medical = List();
    if (projectViewModel.havePrivilege(5)) {
      medical.add(InkWell(
        onTap: () {
          Navigator.push(
            context,
            FadePage(
              page: MyAppointments(),
            ),
          );
        },
        child: isLogin
            ? Stack(children: [
                MedicalProfileItem(
                  title: TranslationBase.of(context).myAppointments,
                  imagePath: 'my_appointment_icon.png',
                  subTitle: TranslationBase.of(context).myAppointmentsList,
                  hasBadge: true,
                ),
                Positioned(
                  right: 0.0,
                  child: Badge(
                    toAnimate: false,
                    position: BadgePosition.topEnd(),
                    shape: BadgeShape.circle,
                    badgeColor: secondaryColor.withOpacity(1.0),
                    borderRadius: BorderRadius.circular(8),
                    badgeContent: Container(
                      padding: EdgeInsets.all(2.0),
                      child: Text(count.toString(),
                          style:
                              TextStyle(color: Colors.white, fontSize: 16.0)),
                    ),
                  ),
                ),
              ])
            : MedicalProfileItem(
                title: TranslationBase.of(context).myAppointments,
                imagePath: 'my_appointment_icon.png',
                subTitle: TranslationBase.of(context).myAppointmentsList,
                hasBadge: true,
              ),
      ));
    }
    if (projectViewModel.havePrivilege(10)) {
      medical.add(InkWell(
        onTap: () => Navigator.push(context, FadePage(page: LabsHomePage())),
        child: MedicalProfileItem(
          title: TranslationBase.of(context).lab,
          imagePath: 'lab_result_icon.png',
          subTitle: TranslationBase.of(context).labSubtitle,
        ),
      ));
    }

    if (projectViewModel.havePrivilege(7)) {
      medical.add(InkWell(
        onTap: () =>
            Navigator.push(context, FadePage(page: RadiologyHomePage())),
        child: MedicalProfileItem(
          title: TranslationBase.of(context).radiology,
          imagePath: 'radiology_icon.png',
          subTitle: TranslationBase.of(context).radiologySubtitle,
        ),
      ));
    }

    if (projectViewModel.havePrivilege(12)) {
      medical.add(InkWell(
        onTap: () {
          Navigator.push(
            context,
            FadePage(
              page: HomePrescriptionsPage(),
            ),
          );
        },
        child: MedicalProfileItem(
          title: TranslationBase.of(context).medicines,
          imagePath: 'prescription_icon.png',
          subTitle: TranslationBase.of(context).medicinesSubtitle,
        ),
      ));
    }

    if (projectViewModel.havePrivilege(25)) {
      medical.add(InkWell(
        onTap: () => Navigator.push(
          context,
          FadePage(
            page: VitalSignDetailsScreen(),
          ),
        ),
        child: MedicalProfileItem(
          title: TranslationBase.of(context).vitalSigns,
          imagePath: 'vital_signs.png',
          subTitle: TranslationBase.of(context).vitalSignsSubtitle,
        ),
      ));
    }

    if (projectViewModel.havePrivilege(48)) {
      medical.add(InkWell(
        onTap: () =>
            Navigator.push(context, FadePage(page: ActiveMedicationsPage())),
        child: MedicalProfileItem(
          title: TranslationBase.of(context).myMedical,
          imagePath: 'active_medications.png',
          subTitle: TranslationBase.of(context).myMedicalSubtitle,
        ),
      ));
    }

    if (projectViewModel.havePrivilege(6)) {
      medical.add(InkWell(
        onTap: () {
          Navigator.push(
            context,
            FadePage(
              page: DoctorHomePage(),
            ),
          );
        },
        child: MedicalProfileItem(
          title: TranslationBase.of(context).myDoctor,
          imagePath: 'doctor_icon.png',
          subTitle: TranslationBase.of(context).myDoctorSubtitle,
        ),
      ));
    }

    if (projectViewModel.havePrivilege(14)) {
      medical.add(InkWell(
        onTap: () {
          Navigator.push(context, FadePage(page: EyeMeasurementsPage()));
        },
        child: MedicalProfileItem(
          title: TranslationBase.of(context).eye,
          imagePath: 'eye_measurement_icon.png',
          subTitle: TranslationBase.of(context).eyeSubtitle,
        ),
      ));
    }
    if (projectViewModel.havePrivilege(22)) {
      medical.add(InkWell(
        onTap: () {
          Navigator.push(context, FadePage(page: InsuranceCard()));
        },
        child: MedicalProfileItem(
          title: TranslationBase.of(context).insurance,
          imagePath: 'insurance_card_icon.png',
          subTitle: TranslationBase.of(context).insuranceSubtitle,
        ),
      ));
    }
    medical.add(InkWell(
      onTap: () {
        Navigator.push(context, FadePage(page: InsuranceUpdate()));
      },
      child: MedicalProfileItem(
        title: TranslationBase.of(context).updateInsurance,
        imagePath: 'insurance_update_icon_.png',
        subTitle: TranslationBase.of(context).updateInsuranceSubtitle,
      ),
    ));

    if (projectViewModel.havePrivilege(18)) {
      medical.add(InkWell(
        onTap: () {
          Navigator.push(context, FadePage(page: InsuranceApproval()));
        },
        child: MedicalProfileItem(
          title: TranslationBase.of(context).insuranceApproval,
          imagePath: 'insurance_approvals_icon.png',
          subTitle: TranslationBase.of(context).insuranceApprovalSubtitle,
        ),
      ));
    }

    if (projectViewModel.havePrivilege(23)) {
      medical.add(InkWell(
        onTap: () => Navigator.push(context, FadePage(page: AllergiesPage())),
        child: MedicalProfileItem(
          title: TranslationBase.of(context).allergies,
          imagePath: 'my_allergies_icon.png',
          subTitle: TranslationBase.of(context).allergiesSubtitle,
        ),
      ));
    }

    if (projectViewModel.havePrivilege(26)) {
      medical.add(InkWell(
        onTap: () {
          Navigator.push(context, FadePage(page: MyVaccines()));
        },
        child: MedicalProfileItem(
          title: TranslationBase.of(context).myVaccines,
          imagePath: 'my_vaccines_icon.png',
          subTitle: TranslationBase.of(context).myVaccinesSubtitle,
        ),
      ));
    }
    if (projectViewModel.havePrivilege(20))
    medical.add(InkWell(
      onTap: () {
        Navigator.push(context, FadePage(page: HomeReportPage()));
      },
      child: MedicalProfileItem(
        title: TranslationBase.of(context).medical,
        imagePath: 'medical_reports_icon.png',
        subTitle: TranslationBase.of(context).medicalSubtitle,
      ),
    ));

    if (projectViewModel.havePrivilege(19)) {
      medical.add(InkWell(
        onTap: () {
          Navigator.push(context, FadePage(page: MonthlyReportsPage()));
        },
        child: MedicalProfileItem(
          title: TranslationBase.of(context).monthly,
          imagePath: 'monthly_reports_icon.png',
          subTitle: TranslationBase.of(context).monthlySubtitle,
        ),
      ));
    }

    if (projectViewModel.havePrivilege(16)) {
      medical.add(InkWell(
        onTap: () {
          Navigator.push(context, FadePage(page: PatientSickLeavePage()));
        },
        child: MedicalProfileItem(
          title: TranslationBase.of(context).sick,
          imagePath: 'sick_leaves_icons.png',
          subTitle: TranslationBase.of(context).sickSubtitle,
        ),
      ));
    }

    if (projectViewModel.havePrivilege(47)) {
      medical.add(InkWell(
        onTap: () {
          Navigator.push(context, FadePage(page: MyBalancePage()));
        },
        child: MedicalProfileItem(
          title: TranslationBase.of(context).myBalance,
          imagePath: 'check-in.png',
          subTitle: TranslationBase.of(context).myBalanceSubtitle,
        ),
      ));
    }

    if (projectViewModel.havePrivilege(61)) {
      medical.add(MedicalProfileItem(
        title: TranslationBase.of(context).patientCall,
        imagePath: 'medical_history_icon.png',
        subTitle: TranslationBase.of(context).patientCallSubtitle,
      ));
    }

    if (projectViewModel.havePrivilege(24)) {
      medical.add(InkWell(
        onTap: () {
          Navigator.push(context, FadePage(page: MyTrackers()));
        },
        child: MedicalProfileItem(
          title: TranslationBase.of(context).myTrackers,
          imagePath: 'my_tracker_icon.png',
          subTitle: TranslationBase.of(context).myTrackersSubtitle,
        ),
      ));
    }
    if (projectViewModel.havePrivilege(30))
    medical.add(InkWell(
      onTap: () {
        Navigator.push(context, FadePage(page: SmartWatchInstructions()));
      },
      child: MedicalProfileItem(
        title: TranslationBase.of(context).smartWatches,
        imagePath: 'smartwatch_icon.png',
        subTitle: TranslationBase.of(context).smartWatchesSubtitle,
      ),
    ));

    if (projectViewModel.havePrivilege(28)) {
      medical.add(InkWell(
        onTap: () {
          Navigator.push(context, FadePage(page: AskDoctorHomPage()));
        },
        child: MedicalProfileItem(
          title: TranslationBase.of(context).askYour,
          imagePath: 'ask_doctor_icon.png',
          subTitle: TranslationBase.of(context).askYourSubtitle,
        ),
      ));
    }
    if (projectViewModel.havePrivilege(32) ||  true) {
      medical.add(InkWell(
          onTap: () {
            userData().then((userData_){
              if (projectViewModel.isLogin && userData_ != null) {
                String patientID = userData_.patientID.toString();
                GifLoaderDialogUtils.showMyDialog(context);
                projectViewModel.platformBridge().connectHMGInternetWifi(patientID).then((value) => {GifLoaderDialogUtils.hideDialog(context)});
              } else {
                AlertDialogBox(
                    context: context,
                    confirmMessage: "Please login with your account first to use this feature",
                    okText: "OK",
                    okFunction: () {
                      AlertDialogBox.closeAlertDialog(context);
                    }).showAlertDialog(context);
              }
            });
          },
        child: MedicalProfileItem(
          title: TranslationBase.of(context).internet,
          imagePath: 'insurance_card_icon.png',
          subTitle: TranslationBase.of(context).internetSubtitle,
        ),
      ));
    }

    if (projectViewModel.havePrivilege(40)) {
      medical.add(InkWell(
//                            onTap: () {
//                              Navigator.push(
//                                  context, FadePage(page: InsuranceApproval()));
//                            },
        child: MedicalProfileItem(
          title: TranslationBase.of(context).chatbot,
          imagePath: 'insurance_approvals_icon.png',
          subTitle: TranslationBase.of(context).chatbotSubtitle,
        ),
      ));
    }

    return medical;
  }
}

Future<AuthenticatedUser> userData() async {
  var userData = AuthenticatedUser.fromJson(await AppSharedPreferences().getObject(MAIN_USER));
  return userData;
}



// extension function that use in iterations(list.. etc) to iterate items and get index and item it self
extension IndexedIterable<E> on Iterable<E> {
  Iterable<T> mapIndexed<T>(T Function(E e, int i) f) {
    var i = 0;
    return map((e) => f(e, i++));
  }
}
/*
  userBoard.asMap().map((i, element) => MapEntry(i, Stack(
  GestureDetector(onTap: () {
  setState(() {
  // print("element=${element.toString()}");
  // print("element=${userBoard[i].toString()}");
  });
  }),
  ))).values.toList();
  */
