import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/core/model/doctor/list_doctor_working_hours_table_model.dart';
import 'package:doctor_app_flutter/core/model/hospitals/get_hospitals_response_model.dart';
import 'package:doctor_app_flutter/core/service/NavigationService.dart';
import 'package:doctor_app_flutter/core/viewModel/authentication_view_model.dart';
import 'package:doctor_app_flutter/core/viewModel/project_view_model.dart';
import 'package:doctor_app_flutter/utils/dr_app_shared_pref.dart';
import 'package:doctor_app_flutter/utils/translations_delegate_base_utils.dart';
import 'package:doctor_app_flutter/widgets/shared/app_texts_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/buttons/app_buttons_widget.dart';
import 'package:doctor_app_flutter/widgets/transitions/fade_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:html/parser.dart';

import '../config/size_config.dart';
import '../locator.dart';
import '../update_page.dart';
import '../utils/dr_app_toast_msg.dart';

DrAppSharedPreferances sharedPref = new DrAppSharedPreferances();

class Utils {
  static int cupertinoPickerIndex = 0;

  get currentLanguage => null;

  static showConfirmationDialog(BuildContext context, String message, Function okFunction, {bool isShowCancelButton = true}) async {
    return await showDialog(
        context: context,
        barrierDismissible: false, // user must tap button!
        builder: (_) {
          return Container(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                AlertDialog(
                  title: null,
                  content: Container(
                    child: AppText(message),
                  ),
                  actions: [
                    AppButton(
                      onPressed: () => okFunction(),
                      title: TranslationBase.of(context).noteConfirm,
                      fontColor: Colors.white,
                      color: AppGlobal.appGreenColor,
                    ),
                    SizedBox(
                      height: 30,
                    ),
                    if (isShowCancelButton)
                      AppButton(
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                        title: TranslationBase.of(context).cancel,
                        fontColor: Colors.white,
                        color: Colors.red[600],
                      ),
                  ],
                ),
              ],
            ),
          );
        });
  }

  static showCupertinoPicker(context, List<GetHospitalsResponseModel> items, decKey, onSelectFun, AuthenticationViewModel model) {
    showModalBottomSheet(
        isDismissible: false,
        context: context,
        builder: (BuildContext builder) {
          return Container(
            // height: 500,
            height: SizeConfig.realScreenHeight! * 0.4,
            color: Color(0xfff7f7f7),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.end,
              children: <Widget>[
                Container(
                  color: Color(0xfff7f7f7),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: <Widget>[
                      CupertinoButton(
                        child: Text(TranslationBase.of(context).cancel, style: textStyle(context)),
                        onPressed: () {
                          Navigator.pop(context);
                        },
                      ),
                      CupertinoButton(
                        child: Text(
                          TranslationBase.of(context).done,
                          style: textStyle(context),
                        ),
                        onPressed: () {
                          Navigator.pop(context);
                          onSelectFun(cupertinoPickerIndex);
                        },
                      )
                    ],
                  ),
                ),
                Container(height: SizeConfig.realScreenHeight! * 0.3, color: Color(0xfff7f7f7), child: buildPickerItems(context, items, decKey, onSelectFun, model))
              ],
            ),
          );
        });
  }

  static TextStyle textStyle(context) => TextStyle(color: Theme.of(context).primaryColor);

  static buildPickerItems(context, List<GetHospitalsResponseModel> items, decKey, onSelectFun, model) {
    return CupertinoPicker(
      magnification: 1.5,
      scrollController: FixedExtentScrollController(initialItem: cupertinoPickerIndex),
      children: items.map((item) {
        return Text(
          '${item.facilityName}',
          style: TextStyle(fontSize: SizeConfig.textMultiplier! * 2),
        );
      }).toList(),
      itemExtent: 25,
      looping: false,
      onSelectedItemChanged: (int index) {
        cupertinoPickerIndex = index;
      },
    );
  }

  static showErrorToast([msg = null]) {
    String localMsg = generateContactAdminMsg();

    if (msg != null) {
      localMsg = msg.toString();
    }

    DrAppToastMsg.showErrorToast(localMsg);
  }

  static Future<bool> checkConnection() async {
    List<ConnectivityResult> connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult.contains(ConnectivityResult.mobile) ||
        connectivityResult.contains(ConnectivityResult.wifi) ||
        connectivityResult.contains(ConnectivityResult.ethernet) ||
        connectivityResult.contains(ConnectivityResult.bluetooth) ||
        connectivityResult.contains(ConnectivityResult.vpn)) {
      return true;
    } else {
      return false;
    }
    // return result.contains(ConnectivityResult.wifi)||result.contains(ConnectivityResult.mobile);
  }

  static List<WorkingHours> getWorkingHours(String workingHours) {
    List<WorkingHours> myWorkingHours = [];
    List<String> listOfHours = workingHours.split('a');

    listOfHours.forEach((element) {
      WorkingHours workingHours = WorkingHours();
      var from = element.substring(element.indexOf('m ') + 2, element.indexOf('To') - 1);
      workingHours.from = from.trim();
      var to = element.substring(element.indexOf('To') + 2);
      workingHours.to = to.trim();
      myWorkingHours.add(workingHours);
    });
    return myWorkingHours;
  }

  static generateContactAdminMsg([err = null]) {
    //TODO: Add translation
    String localMsg = 'Something wrong happened, please contact the admin';
    if (err != null) {
      localMsg = localMsg + '\n \n' + err.toString();
    }
    return localMsg;
  }

  static clearSharedPref() async {
    await sharedPref.clear();
  }

  static getCardBoxDecoration() {
    return BoxDecoration(
      borderRadius: BorderRadius.circular(10),
      color: Colors.white,
      shape: BoxShape.rectangle,
      boxShadow: [
        BoxShadow(
          color: Color(0xFF0000000D),
          spreadRadius: 10,
          blurRadius: 27,
          offset: Offset(0, -3), // changes position of shadow
        ),
      ],
    );
  }

  navigateToUpdatePage(String message, String androidLink, iosLink) {
    locator<NavigationService>().pushAndRemoveUntil(
      FadePage(
        page: UpdatePage(
          message: message,
          androidLink: androidLink,
          iosLink: iosLink,
        ),
      ),
    );

    // Navigator.pushAndRemoveUntil(
    //     AppGlobal.CONTEX,
    //     FadePage(
    //       page: UpdatePage(
    //         message: message,
    //         androidLink: androidLink,
    //         iosLink: iosLink,
    //       ),
    //     ),
    //     (r) => false);
  }

  static String parseHtmlString(String htmlString) {
    final document = parse(htmlString);
    final String parsedString = parse(document.body!.text).documentElement!.text;

    return parsedString;
  }

  static InputDecoration textFieldSelectorDecoration(String hintText, String selectedText, bool isDropDown, {Icon? suffixIcon, Color? dropDownColor}) {
    return InputDecoration(
      focusedBorder: OutlineInputBorder(
        borderSide: BorderSide(color: Color(0xFFCCCCCC), width: 2.0),
        borderRadius: BorderRadius.circular(8),
      ),
      enabledBorder: OutlineInputBorder(
        borderSide: BorderSide(color: Color(0xFFCCCCCC), width: 2.0),
        borderRadius: BorderRadius.circular(8),
      ),
      disabledBorder: OutlineInputBorder(
        borderSide: BorderSide(color: Color(0xFFCCCCCC), width: 2.0),
        borderRadius: BorderRadius.circular(8),
      ),
      hintText: selectedText != null ? selectedText : hintText,
      suffixIcon: isDropDown
          ? suffixIcon != null
              ? suffixIcon
              : Icon(
                  Icons.arrow_drop_down,
                  color: dropDownColor != null ? dropDownColor : Colors.black,
                )
          : null,
      hintStyle: TextStyle(
        fontSize: 14,
        color: Colors.grey.shade600,
      ),
    );
  }

  static BoxDecoration containerBorderDecoration(Color containerColor, Color borderColor, {double borderWidth = -1}) {
    return BoxDecoration(
      color: containerColor,
      shape: BoxShape.rectangle,
      borderRadius: BorderRadius.all(Radius.circular(8)),
      border: Border.fromBorderSide(BorderSide(
        color: borderColor,
        width: borderWidth == -1 ? 2.0 : borderWidth,
      )),
    );
  }

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

  static String capitalize(str) {
    if (str != "") {
      return "${str[0].toUpperCase()}${str.substring(1).toLowerCase()}";
    } else {
      return str;
    }
  }

  static bool isTextHtml(String text) {
    var htmlRegex = RegExp("<(“[^”]*”|'[^’]*’|[^'”>])*>");
    return htmlRegex.hasMatch(text);
  }

  static String timeFrom({required Duration duration}) {
    String twoDigits(int n) => n.toString().padLeft(2, "0");
    String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
    String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
    return "$twoDigitMinutes:$twoDigitSeconds";
  }

  static double getTextFieldHeight() {
    return SizeConfig.heightMultiplier! *
        (SizeConfig.isHeightVeryShort
            ? 10
            : SizeConfig.isHeightShort
                ? 8
                : 6);
  }

  static getLabelFromKPI(String kpi) {
    if (kpi.indexOf("(") > -1 && kpi.indexOf(")") > -1)
      return kpi.substring(kpi.indexOf("(") + 1, kpi.indexOf(")"));
    else
      return '';
  }

  static getNameFromKPI(String kpi) {
    if (kpi.indexOf("(") > -1)
      return kpi.substring(0, kpi.indexOf("("));
    else
      return kpi;
  }

  static String convertToTitleCase(String? text) {
    if (text == null) {
      return "";
    }

    if (text.length <= 1) {
      return text.toUpperCase();
    }

    // Split string into multiple words
    final List<String> words = text.split(' ');

    // Capitalize first letter of each words
    final capitalizedWords = words.map((word) {
      if (word.trim().isNotEmpty) {
        final String firstLetter = word.trim().substring(0, 1).toUpperCase();
        final String remainingLetters = word.trim().substring(1).toLowerCase();

        return '$firstLetter$remainingLetters';
      }
      return '';
    });

    // Join/Merge all words back to one String
    return capitalizedWords.join(' ');
  }

  static bool isVidaPlusProject(ProjectViewModel projectViewModel, int projectID) {
    bool isVidaPlus = false;
    projectViewModel.vidaPlusProjectList.forEach((element) {
      if (element.projectID == projectID) {
        isVidaPlus = true;
      }
    });
    return isVidaPlus;
  }

  static bool isVidaPlusInPatientProject(ProjectViewModel projectViewModel, int projectID) {
    bool isVidaPlusInPatientProject = false;
    projectViewModel.vidaPlusInPatientsProjectListModel.forEach((element) {
      if (element.projectID == projectID) {
        isVidaPlusInPatientProject = true;
      }
    });
    return isVidaPlusInPatientProject;
  }
}
