import 'package:hmg_patient_app/config/shared_pref_kay.dart';
import 'package:hmg_patient_app/core/service/weather_service.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/locator.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/E-Referral/e_referral_page.dart';
import 'package:hmg_patient_app/pages/AlHabibMedicalService/ancillary-orders/ancillaryOrders.dart';
import 'package:hmg_patient_app/pages/AlHabibMedicalService/health-weather/health-weather-indicator.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/child_vaccines_page.dart';
import 'package:hmg_patient_app/pages/ChildVaccines/new/child_initial_page.dart';
import 'package:hmg_patient_app/pages/ChildVaccines/new/child_vaccine_page.dart';
import 'package:hmg_patient_app/pages/ContactUs/findus/findus_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/ErOptions.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/landing/landing_page_pharmcy.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/uitl/app_shared_preferences.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/translations_delegate_base.dart';
import 'package:hmg_patient_app/widgets/data_display/services)contaniner.dart';
import 'package:hmg_patient_app/widgets/data_display/text.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:geolocator/geolocator.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';

import 'h2o/h2o_page.dart';

class AllHabibMedicalService extends StatefulWidget {
  //TODO
  final Function? goToMyProfile;

  AllHabibMedicalService({Key? key,  this.goToMyProfile});

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

class _AllHabibMedicalServiceState extends State<AllHabibMedicalService> {
  AppSharedPreferences sharedPref = AppSharedPreferences();
  AuthenticatedUser authUser = new AuthenticatedUser();
  AuthProvider authProvider = new AuthProvider();
  PharmacyModuleViewModel pharmacyModuleViewModel = locator<PharmacyModuleViewModel>();
  late LocationUtils locationUtils;
  var weather = '--';
  WeatherService _weatherService = WeatherService();
  List<HmgServices> hmgServices = [];

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      locationUtils = new LocationUtils(isShowConfirmDialog: true, context: context);
      WidgetsBinding.instance.addPostFrameCallback((_) => {Geolocator.getLastKnownPosition().then((value) => setLocation(value!))});
    });
    super.initState();
  }

  initialiseHmgServices(bool isLogin) {
    hmgServices.clear();
    hmgServices.add(new HmgServices(0, TranslationBase.of(context).liveCare, TranslationBase.of(context).onlineConsulting, "assets/images/new/Live_Care.svg", isLogin));
    hmgServices.add(new HmgServices(1, TranslationBase.of(context).covidTest, TranslationBase.of(context).driveThru, "assets/images/new/covid_test_drive_thru.svg", isLogin));
    hmgServices.add(new HmgServices(2, TranslationBase.of(context).online, TranslationBase.of(context).payment, "assets/images/new/visa.png", isLogin));
    hmgServices.add(new HmgServices(3, TranslationBase.of(context).hhcHome, TranslationBase.of(context).healthCare, "assets/images/new/HHC.svg", isLogin));
    hmgServices.add(new HmgServices(4, TranslationBase.of(context).checkup, TranslationBase.of(context).comprehensive, "assets/images/new/comprehensive_checkup.svg", isLogin));
    hmgServices.add(new HmgServices(5, "RRT", TranslationBase.of(context).emergency, "assets/images/new/emergency.svg", isLogin));
    hmgServices.add(new HmgServices(6, TranslationBase.of(context).refferal, TranslationBase.of(context).services2, "assets/images/new/E_Referral.svg", isLogin));
    hmgServices.add(new HmgServices(7, "H\u2082O", TranslationBase.of(context).dailyWater, "assets/images/new/h2o.svg", isLogin));
    hmgServices.add(new HmgServices(8, TranslationBase.of(context).reachUs, TranslationBase.of(context).findUs, "assets/images/new/reach_us.svg", isLogin));
  }

  @override
  Widget build(BuildContext context) {
    ProjectViewModel projectViewModel = Provider.of(context);
    initialiseHmgServices(false);
    return AppScaffold(
      isShowAppBar: true,
      appBarTitle: TranslationBase.of(context).alhabiServices,
      isShowDecPage: false,
      body: Column(
        children: [
          Expanded(
            child: ListView(
              scrollDirection: Axis.vertical,
              physics: AlwaysScrollableScrollPhysics(),
              shrinkWrap: true,
              children: [
                Container(
                  margin: EdgeInsets.all(8),
                  width: double.infinity,
                  height: 150,
                  decoration: BoxDecoration(
                      image: DecorationImage(
                        image: ExactAssetImage('assets/images/Weather_img.png'),
                        fit: BoxFit.cover,
                      ),
                      borderRadius: BorderRadius.circular(8.0)),
                  child: Padding(
                    padding: EdgeInsets.symmetric(horizontal: 10.0),
                    child: Row(
                      children: [
                        Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Texts(
                              TranslationBase.of(context).healthWeatherIndicators,
                              color: Colors.white,
                              fontWeight: FontWeight.w600,
                            ),
                            Texts(
                              TranslationBase.of(context).healthTipsBasedOnCurrentWeather,
                              color: Colors.white,
                              fontSize: 14,
                            ),
                          ],
                        ),
                        Expanded(
                          flex: 2,
                          child: InkWell(
                              onTap: () {
                                Navigator.push(
                                  context,
                                  FadePage(
                                    page: HealthWeatherIndicator(),
                                  ),
                                );
                              },
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Image.asset(
                                        'assets/images/Weather_ico.png',
                                        width: 60,
                                        height: 60,
                                      ),
                                      Directionality(textDirection: TextDirection.ltr, child: AppText(weather, fontSize: 22, color: Colors.white))
                                    ],
                                  ),
                                  Texts(
                                    TranslationBase.of(context).moreDetails,
                                    color: Colors.white,
                                    decoration: TextDecoration.underline,
                                  ),
                                ],
                              )),
                        )
                      ],
                    ),
                  ),
                ),
                ServicesContainer(
                  onTap: () {
                    Navigator.pop(context);
                    Navigator.push(
                      context,
                      FadePage(
                        page: MedicalProfilePageNew(),
                      ),
                    );
                  },
                  imageLocation: 'assets/images/new-design/my_file_bottom_bar.png',
                  title: TranslationBase.of(context).myMedicalFile,
                ),
                ServicesContainer(
                  onTap: () => Navigator.push(
                    context,
                    FadePage(
                      page: LiveCareHome(),
                    ),
                  ),
                  imageLocation: 'assets/images/new-design/liveCare_ar_bg.png',
                  title: TranslationBase.of(context).livecare,
                ),
                ServicesContainer(
                  onTap: () => Navigator.push(
                    context,
                    FadePage(
                      page: Search(),
                    ),
                  ),
                  imageLocation: 'assets/images/new-design/booking_icon_active.png',
                  title: TranslationBase.of(context).bookAppo,
                ),
                ServicesContainer(
                  onTap: () => Navigator.push(
                    context,
                    FadePage(
                      page: PaymentService(),
                    ),
                  ),
                  imageLocation: 'assets/images/al-habib_online_payment_service_icon.png',
                  title: TranslationBase.of(context).onlinePaymentService,
                ),
                ServicesContainer(
                  onTap: () => Navigator.push(
                    context,
                    FadePage(
                      page: AnicllaryOrders(),
                    ),
                  ),
                  imageLocation: 'assets/images/comprehensive_medical_checkup_logo.png',
                  title: TranslationBase.of(context).anicllaryOrders,
                ),
                ServicesContainer(
                  onTap: () => Navigator.push(
                    context,
                    FadePage(page: CovidDrivethruLocation()),
                  ),
                  imageLocation: 'assets/images/covid-car.png',
                  title: TranslationBase.of(context).covid19_driveThrueTest,
                ),
                ServicesContainer(
                  onTap: () {
                    Navigator.push(
                      context,
                      FadePage(
                        page: ErOptions(
                          isAppbar: true,
                        ),
                      ),
                    );
                  },
                  imageLocation: 'assets/images/emergency_service_image.png',
                  title: TranslationBase.of(context).emergencyService,
                ),
                ServicesContainer(onTap: () => getPharmacyToken(), imageLocation: 'assets/images/pharmacy_logo.png', title: TranslationBase.of(context).pharmacy),
                ServicesContainer(
                  onTap: () => Navigator.push(
                    context,
                    FadePage(
                      page: InsuranceUpdate(),
                    ),
                  ),
                  imageLocation: 'assets/images/medical/insurance_card_icon.png',
                  title: TranslationBase.of(context).updateInsurance,
                ),
                ServicesContainer(
                  onTap: () => Navigator.push(
                    context,
                    FadePage(page: EReferralPage()),
                  ),
                  imageLocation: 'assets/images/ereferral_service_icon.png',
                  title: TranslationBase.of(context).ereferral,
                ),
                ServicesContainer(
                  onTap: () => Navigator.push(
                    context,
                    FadePage(
                      page: MyFamily(),
                    ),
                  ),
                  imageLocation: 'assets/images/new-design/family_icon_bottom_bar.png',
                  title: TranslationBase.of(context).myFamily,
                ),
                if (projectViewModel.havePrivilege(35))
                  ServicesContainer(
                    onTap: () => Navigator.push(
                      context,
                      FadePage(page: ChildInitialPage()),
                    ),
                    imageLocation: 'assets/images/new-design/children_vaccines_icon.png',
                    title: TranslationBase.of(context).childVaccine,
                  ),
                ServicesContainer(
                  onTap: () {
                    Navigator.pop(context);
                    LandingPage.shared.switchToDoFromHMGServices();
                  },
                  imageLocation: 'assets/images/new-design/upcoming_icon_bottom_bar.png',
                  title: TranslationBase.of(context).todoList,
                ),
                if (projectViewModel.havePrivilege(36))
                  ServicesContainer(
                    onTap: () => Navigator.push(
                      context,
                      FadePage(page: BloodDonationPage()),
                    ),
                    imageLocation: 'assets/images/new-design/blood_icon.png',
                    title: TranslationBase.of(context).bloodD,
                  ),
                ServicesContainer(
                  onTap: () => Navigator.push(
                    context,
                    FadePage(
                      page: (HealthCalculators()),
                    ),
                  ),
                  imageLocation: 'assets/images/new-design/health_calculator_icon.png',
                  title: TranslationBase.of(context).calculators,
                ),
                ServicesContainer(
                  onTap: () => Navigator.push(
                    context,
                    FadePage(
                      page: HealthConverter(),
                    ),
                  ),
                  imageLocation: 'assets/images/new-design/health_convertor_icon.png',
                  title: TranslationBase.of(context).converters,
                ),
                if (projectViewModel.havePrivilege(38))
                  ServicesContainer(
                    onTap: () => Navigator.push(context, FadePage(page: H2OPage())),
                    imageLocation: 'assets/images/new-design/water_icon.png',
                    title: TranslationBase.of(context).h2o,
                  ),
                if (projectViewModel.havePrivilege(41))
                  ServicesContainer(
                    onTap: () => Navigator.push(
                      context,
                      FadePage(page: SmartWatchInstructions()),
                    ),
                    imageLocation: 'assets/images/new-design/smartwatch_icon.png',
                    title: TranslationBase.of(context).smartWatches,
                  ),
                ServicesContainer(
                  onTap: () => Navigator.push(
                    context,
                    FadePage(
                      page: ParkingPage(),
                    ),
                  ),
                  imageLocation: 'assets/images/new-design/parking_system_icon.png',
                  title: TranslationBase.of(context).parking,
                ),
                ServicesContainer(
                  onTap: () => launch("https://hmgwebservices.com/vt_mobile/html/index.html"),
                  imageLocation: 'assets/images/new-design/virtual_tour_icon.png',
                  title: TranslationBase.of(context).vTour,
                ),
                ServicesContainer(
                  onTap: () {
                    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", //this url is not working so changed to the hmg
                            )));
                  },
                  imageLocation: 'assets/images/new-design/twitter_dashboard_icon.png',
                  title: TranslationBase.of(context).latestNews,
                ),
                ServicesContainer(
                  onTap: () => Navigator.push(
                    context,
                    FadePage(
                      page: FindUsPage(),
                    ),
                  ),
                  imageLocation: 'assets/images/new-design/find_us_icon.png',
                  title: TranslationBase.of(context).findUs,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

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

  getAuthUser() async {
    if (await this.sharedPref.getObject(USER_PROFILE) != null) {
      var data = AuthenticatedUser.fromJson(await this.sharedPref.getObject(USER_PROFILE));
      setState(() {
        authUser = data;
      });
    }
    var data = await this.sharedPref.getObject(WEATHER);
    if (data == null) {
      var d = await _weatherService.getWeatherData();
      print(d);
      setState(() {
        weather = d != null ? d.temperature.toString() + '\u2103' : '--';
      });
    } else {
      setState(() {
        weather = data != null ? data['Temperature'].toString() + '\u2103' : '--';
      });
    }
  }

  void setLocation(Position position) {
    this.sharedPref.setDouble(USER_LAT, position.latitude ?? 0.0);
    this.sharedPref.setDouble(USER_LONG, position.longitude ?? 0.0);
    getAuthUser();
  }
}
