import 'dart:io';

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/size_config.dart';
import 'package:hmg_patient_app/core/model/hospitals/hospitals_model.dart';
import 'package:hmg_patient_app/core/viewModels/pharmacyModule/pharmacy_module_view_model.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/models/Authentication/authenticated_user.dart';
import 'package:hmg_patient_app/models/hmg_services.dart';
import 'package:hmg_patient_app/pages/AlHabibMedicalService/%E2%80%8B%20health_calculators.dart';
import 'package:hmg_patient_app/pages/AlHabibMedicalService/ComprehensiveMedicalCheckup/cmc_page.dart';
import 'package:hmg_patient_app/pages/AlHabibMedicalService/E-Referral/e_referral_page.dart';
import 'package:hmg_patient_app/pages/AlHabibMedicalService/HomeHealthCare/home_health_care_page.dart';
import 'package:hmg_patient_app/pages/AlHabibMedicalService/h2o/h2o_page.dart';
import 'package:hmg_patient_app/pages/AlHabibMedicalService/health_converter.dart';
import 'package:hmg_patient_app/pages/AlHabibMedicalService/my_web_view.dart';
import 'package:hmg_patient_app/pages/AlHabibMedicalService/parking_page.dart';
import 'package:hmg_patient_app/pages/Blood/blood_donation.dart';
import 'package:hmg_patient_app/pages/BookAppointment/Search.dart';
import 'package:hmg_patient_app/pages/ChildVaccines/new/child_initial_page.dart';
import 'package:hmg_patient_app/pages/ContactUs/contact_us_page.dart';
import 'package:hmg_patient_app/pages/Covid-DriveThru/covid-drivethru-location.dart';
import 'package:hmg_patient_app/pages/DrawerPages/family/my-family.dart';
import 'package:hmg_patient_app/pages/ErService/EROnlineCheckIn/EROnlineCheckInHome.dart';
import 'package:hmg_patient_app/pages/ErService/ErOptions.dart';
import 'package:hmg_patient_app/pages/InPatientServices/inpatient_home.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/livecare/livecare_home.dart';
import 'package:hmg_patient_app/pages/medical/medical_profile_page_new.dart';
import 'package:hmg_patient_app/pages/medical/smart_watch_health_data/smart_watch_instructions.dart';
import 'package:hmg_patient_app/pages/paymentService/payment_service.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-permissions.dart';
import 'package:hmg_patient_app/uitl/gif_loader_dialog_utils.dart';
import 'package:hmg_patient_app/uitl/location_util.dart';
import 'package:hmg_patient_app/uitl/penguin_method_channel.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/dialogs/covid_consent_dialog.dart';
import 'package:hmg_patient_app/widgets/dialogs/location_selection_dialog.dart';
import 'package:hmg_patient_app/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../../locator.dart';
import '../landing_page_pharmcy.dart';

class ServicesView extends StatelessWidget {
  HmgServices hmgServices;
  int index;
  AuthenticatedUser authUser = new AuthenticatedUser();
  AuthProvider authProvider = new AuthProvider();
  PharmacyModuleViewModel pharmacyModuleViewModel = locator<PharmacyModuleViewModel>();
  late LocationUtils locationUtils;
  bool isHomePage;
  late ProjectViewModel projectViewModel;
  bool isLocked;

  ServicesView(this.hmgServices, this.index, this.isHomePage, this.projectViewModel, {this.isLocked = false});

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {
        if (isHomePage) {
          handleHomePageServices(hmgServices, context);
        } else {
          handleAllServices(hmgServices, context);
        }
      },
      child: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: containerRadiusWithGradientServices(20, lightColor: CustomColors.lightGreyColor, darkColor: CustomColors.darkGreyColor),
        child: Stack(
          children: [
            Container(
              width: double.infinity,
              height: double.infinity,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  mFlex(1),
                  Flexible(
                    flex: 8,
                    child: Column(
                      children: [
                        Flexible(
                          flex: 5,
                          child: Padding(
                            padding: const EdgeInsets.all(12.0),
                            child: Opacity(
                              opacity: 0.04,
                              child: hmgServices.action == 5
                                  ? Image.asset(
                                      hmgServices.icon,
                                      width: double.infinity,
                                      height: double.infinity,
                                    )
                                  : SvgPicture.asset(
                                      hmgServices.icon,
                                      width: double.infinity,
                                      height: double.infinity,
                                    ),
                            ),
                          ),
                        ),
                        mFlex(1),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            Container(
              width: double.infinity,
              height: double.infinity,
              padding: EdgeInsets.only(left: SizeConfig.widthMultiplier! * 3, right: SizeConfig.widthMultiplier! * 3, top: SizeConfig.widthMultiplier! * 3, bottom: SizeConfig.widthMultiplier! * 2),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  mFlex(1),
                  hmgServices.action == (isHomePage ? 5 : 8)
                      ? Image.asset(
                          hmgServices.icon,
                          height: index == 0 ? MediaQuery.of(context).size.width / 18 : MediaQuery.of(context).size.width / 18,
                        )
                      : Container(
                          // color: Colors.yellow,
                          width: index == 4 ? MediaQuery.of(context).size.width / 12 : MediaQuery.of(context).size.width / 12,
                          height: index == 4 ? MediaQuery.of(context).size.width / 10 : MediaQuery.of(context).size.width / 12,
                          child: SvgPicture.asset(
                            hmgServices.icon,
// width: MediaQuery.of(context).size.width / 12,
                            // height: MediaQuery.of(context).size.width / 12,
                          ),
                        ),
                  mFlex(4),
                  AutoSizeText(
                    hmgServices.title,
                    maxLines: 1,
                    minFontSize: 10,
                    style: TextStyle(
                      fontSize: SizeConfig.textMultiplier! * 1.6,
                      fontWeight: FontWeight.bold,
                      letterSpacing: -0.39,
                      height: 0.8,
                    ),
                  ),
                  AutoSizeText(
                    hmgServices.subTitle,
                    maxLines: 1,
                    minFontSize: 8,
                    style: TextStyle(
                      fontSize: SizeConfig.textMultiplier! * 1.4,
                      letterSpacing: -0.27,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  mFlex(1),
                ],
              ),
            ),
            isLocked
                ? Container(
                    width: double.infinity,
                    height: double.infinity,
                    decoration: containerRadiusWithGradientServices(20, lightColor: Colors.grey.withOpacity(0.6), darkColor: Colors.grey.withOpacity(0.6)),
                    child: Icon(
                      Icons.lock_outline,
                      size: 40,
                    ),
                  )
                : Container()
          ],
        ),
      ),
    );
  }

  openNavigationProjectSelection(BuildContext context) {
    int _selectedHospitalIndex = 0;
    List<HospitalsModel> projectsListLocal = [];
    Utils.navigationProjectsList.forEach((v) {
      projectsListLocal.add(new HospitalsModel.fromJson(v));
    });
    showDialog(
      context: context,
      builder: (cxt) => LocationSelectionDialog(
        isArabic: projectViewModel.isArabic,
        data: projectsListLocal,
        selectedIndex: _selectedHospitalIndex,
        onValueSelected: (index) {
          _selectedHospitalIndex = index;
          initPenguinSDK(projectsListLocal[index].iD);
        },
      ),
    );
  }

  initPenguinSDK(int projectID) async {
    final bool permited = await AppPermission.askPenguinPermissions();
    if (!permited) {
      Map<Permission, PermissionStatus> statuses = await [
        Permission.location,
        Permission.bluetooth,
        Permission.bluetoothConnect,
        Permission.bluetoothScan,
        Permission.activityRecognition,
      ].request().whenComplete(() {
        PenguinMethodChannel().launch("penguin", projectViewModel.isArabic ? "ar" : "en", projectViewModel.authenticatedUserObject.user.patientID.toString());
      });
    }
  }

  handleHomePageServices(HmgServices hmgServices, BuildContext context) {
    if (hmgServices.action == 0) {
      Navigator.push(context, FadePage(page: Search()));
      locator<GAnalytics>().hmgServices.logServiceName('book appointment');
    } else if (hmgServices.action == 1) {
      openLiveCare(context);
    } else if (hmgServices.action == 2) {
      //todo for temporary basis
      // Navigator.push(context, FadePage(page: VitalSigns()));

      // initPenguinSDK();
      if (projectViewModel.isIndoorNavigationEnabled) {
        if (!isLocked) openNavigationProjectSelection(context);
      } else {
        Navigator.push(context, FadePage(page: ErOptions(isAppbar: true)));
        locator<GAnalytics>().hmgServices.logServiceName('emergency service');
      }
    } else if (hmgServices.action == 3) {
      Navigator.push(context, FadePage(page: HomeHealthCarePage()));
      locator<GAnalytics>().hmgServices.logServiceName('home health care');
    } else if (hmgServices.action == 4) {
      Navigator.push(context, FadePage(page: CMCPage()));
      locator<GAnalytics>().hmgServices.logServiceName('comprehensive medical checkup');
    } else if (hmgServices.action == 5) {
      Navigator.push(context, FadePage(page: PaymentService()));
      locator<GAnalytics>().hmgServices.logServiceName('online payments');
    } else if (hmgServices.action == 6) {
      Navigator.push(context, FadePage(page: EReferralPage()));
      locator<GAnalytics>().hmgServices.logServiceName('e-referral service');
    } else if (hmgServices.action == 7) {
      showCovidDialog(context);
      locator<GAnalytics>().hmgServices.logServiceName('covid-test drive-thru');
    } else if (hmgServices.action == 8) {
      Navigator.push(context, FadePage(page: ContactUsPage()));
      locator<GAnalytics>().hmgServices.logServiceName('find us reach us');
    } else if (hmgServices.action == 23) {
      Navigator.push(context, FadePage(page: InPatientServicesHome()));
      locator<GAnalytics>().hmgServices.logServiceName('find us reach us');
    } else if (hmgServices.action == 9) {
      if (!isLocked) Navigator.push(context, FadePage(page: EROnlineCheckInHomePage()));
      locator<GAnalytics>().hmgServices.logServiceName('ER Online CheckIn');
    }
  }

  handleAllServices(HmgServices hmgServices, BuildContext context) {
    if (hmgServices.action == 0) {
      Navigator.push(context, FadePage(page: Search()));
      locator<GAnalytics>().hmgServices.logServiceName('book appointment');
    } else if (hmgServices.action == 1) {
      openLiveCare(context);
    } else if (hmgServices.action == 2) {
      Navigator.push(context, FadePage(page: ErOptions(isAppbar: true)));
      locator<GAnalytics>().hmgServices.logServiceName('emergency service');
    } else if (hmgServices.action == 3) {
      Navigator.push(context, FadePage(page: HomeHealthCarePage()));
      locator<GAnalytics>().hmgServices.logServiceName('home health care');
    } else if (hmgServices.action == 4) {
      Navigator.push(context, FadePage(page: CMCPage()));
      locator<GAnalytics>().hmgServices.logServiceName('comprehensive medical checkup');
    } else if (hmgServices.action == 5) {
      // getPharmacyToken(context);
      Uri uri = Uri.parse(PHARMACY_REDIRECT_URL);
      launchUrl(uri, mode: LaunchMode.externalApplication);
      locator<GAnalytics>().hmgServices.logServiceName('al habib pharmacy');
    } else if (hmgServices.action == 6) {
      Navigator.push(context, FadePage(page: MedicalProfilePageNew()));
    } else if (hmgServices.action == 7) {
      Navigator.push(context, FadePage(page: MyFamily()));
      locator<GAnalytics>().hmgServices.logServiceName('my family files');
    } else if (hmgServices.action == 8) {
      Navigator.push(context, FadePage(page: PaymentService()));
      locator<GAnalytics>().hmgServices.logServiceName('online payments');
    } else if (hmgServices.action == 9) {
      Navigator.push(context, FadePage(page: ChildInitialPage()));
      locator<GAnalytics>().hmgServices.logServiceName('my child vaccines');
    } else if (hmgServices.action == 10) {
      Navigator.push(context, FadePage(page: InsuranceUpdate()));
      locator<GAnalytics>().hmgServices.logServiceName('update insurance');
    } else if (hmgServices.action == 11) {
      Navigator.push(context, FadePage(page: EReferralPage()));
      locator<GAnalytics>().hmgServices.logServiceName('e-referral service');
    } else if (hmgServices.action == 12) {
      Navigator.push(context, FadePage(page: H2OPage()));
      locator<GAnalytics>().hmgServices.logServiceName('water consumption');
    } else if (hmgServices.action == 13) {
      Navigator.push(context, FadePage(page: (HealthCalculators())));
      locator<GAnalytics>().hmgServices.logServiceName('health calculator');
    } else if (hmgServices.action == 14) {
      Navigator.push(context, FadePage(page: HealthConverter()));
      locator<GAnalytics>().hmgServices.logServiceName('heath converters');
    } else if (hmgServices.action == 15) {
      Navigator.pop(context);
      LandingPage.shared.switchToDoFromHMGServices();
      locator<GAnalytics>().hmgServices.logServiceName('todo list');
    } else if (hmgServices.action == 16) {
      Navigator.push(context, FadePage(page: BloodDonationPage()));
      locator<GAnalytics>().hmgServices.logServiceName('blood donation');
    } else if (hmgServices.action == 17) {
      showCovidDialog(context);
      locator<GAnalytics>().hmgServices.logServiceName('covid-test drive-thru');
    } else if (hmgServices.action == 18) {
      launch("https://hmgwebservices.com/vt_mobile/html/index.html");
      locator<GAnalytics>().hmgServices.logServiceName('virtual tour');
    } else if (hmgServices.action == 19) {
      Navigator.push(context, FadePage(page: SmartWatchInstructions()));
      locator<GAnalytics>().hmgServices.logServiceName('smart watches');
    } else if (hmgServices.action == 20) {
      Navigator.push(context, FadePage(page: ParkingPage()));
      locator<GAnalytics>().hmgServices.logServiceName('car parcking service');
    } else if (hmgServices.action == 21) {
      Navigator.of(context).push(
        MaterialPageRoute(
          builder: (BuildContext context) => MyWebView(title: "HMG News", selectedUrl: "https://twitter.com/hmg" //"https://twitter.com/hashtag/مجموعة_د_سليمان_الحبيب_الطبية?src=hashtag_click&f=live",
              ),
        ),
      );
      locator<GAnalytics>().hmgServices.logServiceName('latest news');
    } else if (hmgServices.action == 22) {
      Navigator.push(context, FadePage(page: ContactUsPage()));
      locator<GAnalytics>().hmgServices.logServiceName('find us reach us');
    }

    // if (hmgServices.action == 10) {
    //   openLiveCare(context);
    // } else if (index == 1) {
    //   showCovidDialog(context);
    //   locator<GAnalytics>().hmgServices.logServiceName('covid-test drive-thru');
    // } else if (index == 2) {
    //   Navigator.push(context, FadePage(page: PaymentService()));
    //   locator<GAnalytics>().hmgServices.logServiceName('online payments');
    // } else if (index == 3) {
    //   Navigator.push(context, FadePage(page: HomeHealthCarePage()));
    //   locator<GAnalytics>().hmgServices.logServiceName('home health care');
    // } else if (index == 4) {
    //   Navigator.push(context, FadePage(page: CMCPage()));
    //   locator<GAnalytics>().hmgServices.logServiceName('comprehensive medical checkup');
    // } else if (index == 5) {
    //   Navigator.push(context, FadePage(page: ErOptions(isAppbar: true)));
    //   locator<GAnalytics>().hmgServices.logServiceName('emergency service');
    // } else if (index == 6) {
    //   Navigator.push(context, FadePage(page: EReferralPage()));
    //   locator<GAnalytics>().hmgServices.logServiceName('e-referral service');
    // } else if (index == 7) {
    //   Navigator.push(context, FadePage(page: H2OPage()));
    //   locator<GAnalytics>().hmgServices.logServiceName('water consumption');
    // } else if (index == 8) {
    //   Navigator.push(context, FadePage(page: ContactUsPage()));
    //   locator<GAnalytics>().hmgServices.logServiceName('find us reach us');
    // } else if (index == 9) {
    //   Navigator.push(
    //     context,
    //     FadePage(
    //       page: MedicalProfilePageNew(),
    //     ),
    //   );
    //   locator<GAnalytics>().hmgServices.logServiceName('my medical details');
    // } else if (index == 10) {
    //   Navigator.push(
    //     context,
    //     FadePage(
    //       page: Search(),
    //     ),
    //   );
    //   locator<GAnalytics>().hmgServices.logServiceName('book appointment');
    // } else if (index == 11) {
    //   getPharmacyToken(context);
    //   locator<GAnalytics>().hmgServices.logServiceName('al habib pharmacy');
    // } else if (index == 12) {
    //   Navigator.push(
    //     context,
    //     FadePage(
    //       page: InsuranceUpdate(),
    //     ),
    //   );
    //   locator<GAnalytics>().hmgServices.logServiceName('update insurance');
    // } else if (index == 13) {
    //   Navigator.push(
    //     context,
    //     FadePage(
    //       page: MyFamily(),
    //     ),
    //   );
    //   locator<GAnalytics>().hmgServices.logServiceName('my family files');
    // } else if (index == 14) {
    //   Navigator.push(
    //     context,
    //     FadePage(page: ChildInitialPage()),
    //   );
    //   locator<GAnalytics>().hmgServices.logServiceName('my child vaccines');
    // } else if (index == 15) {
    //   LandingPage.shared.switchToDoFromHMGServices();
    //   locator<GAnalytics>().hmgServices.logServiceName('todo list');
    // } else if (index == 16) {
    //   Navigator.push(
    //     context,
    //     FadePage(page: BloodDonationPage()),
    //   );
    //   locator<GAnalytics>().hmgServices.logServiceName('blood donation');
    // } else if (index == 17) {
    //   Navigator.push(
    //     context,
    //     FadePage(
    //       page: (HealthCalculators()),
    //     ),
    //   );
    //   locator<GAnalytics>().hmgServices.logServiceName('health calculator');
    // } else if (index == 18) {
    //   Navigator.push(
    //     context,
    //     FadePage(
    //       page: HealthConverter(),
    //     ),
    //   );
    //   locator<GAnalytics>().hmgServices.logServiceName('heath converters');
    // } else if (index == 19) {
    //   Navigator.push(
    //     context,
    //     FadePage(page: SmartWatchInstructions()),
    //   );
    //   locator<GAnalytics>().hmgServices.logServiceName('smart watches');
    // } else if (index == 20) {
    //   locator<GAnalytics>().hmgServices.logServiceName('car parcking service');
    //   Navigator.push(
    //     context,
    //     FadePage(
    //       page: ParkingPage(),
    //     ),
    //   );
    // } else if (index == 21) {
    //   launch("https://hmgwebservices.com/vt_mobile/html/index.html");
    //   locator<GAnalytics>().hmgServices.logServiceName('virtual tour');
    // } else if (index == 22) {
    //   Navigator.of(context).push(
    //     MaterialPageRoute(
    //       builder: (BuildContext context) => MyWebView(
    //         title: "HMG News",
    //         selectedUrl: "https://twitter.com/hashtag/مجموعة_د_سليمان_الحبيب_الطبية?src=hashtag_click&f=live",
    //       ),
    //     ),
    //   );
    //   locator<GAnalytics>().hmgServices.logServiceName('latest news');
    // }
  }

  showCovidDialog(BuildContext context) {
    if (Platform.isAndroid) {
      showDialog(
          context: context,
          builder: (cxt) => CovidConsentDialog(
                okTitle: TranslationBase.of(context).acceptLbl,
                title: TranslationBase.of(context).covidConsentHeader,
                message: TranslationBase.of(context).covidConsent,
                onTap: () async {
                  Navigator.push(context, FadePage(page: CovidDrivethruLocation()));
                },
              ));
    } else {
      Navigator.push(context, FadePage(page: CovidDrivethruLocation()));
    }
  }

  openLiveCare(BuildContext context) {
    locator<GAnalytics>().hmgServices.logServiceName('live care service');
    Navigator.push(context, FadePage(page: LiveCareHome())).then((value) {
      LiveCareHome.isLiveCareTypeSelected = false;
    });
  }

  getPharmacyToken(BuildContext context) async {
    if (!authProvider.isLogin) {
      Navigator.push(context, FadePage(page: LandingPagePharmacy()));
    } else {
      GifLoaderDialogUtils.showMyDialog(context);
      await pharmacyModuleViewModel.generatePharmacyToken().then((value) async {
        if (pharmacyModuleViewModel.error.isNotEmpty) {
          await pharmacyModuleViewModel.createUser().then((value) {
            GifLoaderDialogUtils.hideDialog(context);
            Navigator.push(context, FadePage(page: LandingPagePharmacy()));
          });
        } else {
          GifLoaderDialogUtils.hideDialog(context);
          Navigator.push(context, FadePage(page: LandingPagePharmacy()));
        }
      });
    }
  }
}
