import 'dart:io';

import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/service/weather_service.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.dart';
import 'package:diplomaticquarterapp/models/hmg_services.dart';
import 'package:diplomaticquarterapp/pages/landing/widgets/services_view.dart';
import 'package:diplomaticquarterapp/services/authentication/auth_provider.dart';
import 'package:diplomaticquarterapp/services/permission/permission_service.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart';
import 'package:diplomaticquarterapp/uitl/date_uitl.dart';
import 'package:diplomaticquarterapp/uitl/location_util.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/uitl/utils.dart';
import 'package:diplomaticquarterapp/uitl/utils_new.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:geolocator/geolocator.dart';
import 'package:provider/provider.dart';

import 'health-weather/health-weather-indicator.dart';

class AllHabibMedicalSevicePage2 extends StatefulWidget {
  @override
  _AllHabibMedicalSevicePage2State createState() => _AllHabibMedicalSevicePage2State();
}

class _AllHabibMedicalSevicePage2State extends State<AllHabibMedicalSevicePage2> {
  List<HmgServices> hmgServices = [];
  LocationUtils locationUtils;
  var weather = '--';
  AppSharedPreferences sharedPref = AppSharedPreferences();
  AuthenticatedUser authUser = new AuthenticatedUser();
  AuthProvider authProvider = new AuthProvider();
  WeatherService _weatherService = WeatherService();
  double weatherNum = 30;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      locationUtils = new LocationUtils(isShowConfirmDialog: true, context: context);
      WidgetsBinding.instance.addPostFrameCallback((_) async => {
            if (await PermissionService.isLocationEnabled())
              {Geolocator.getLastKnownPosition().then((value) => setLocation(value))}
            else
              {
                if (Platform.isAndroid)
                  {
                    Utils.showPermissionConsentDialog(context, TranslationBase.of(context).locationPermissionDialog, () {
                      Geolocator.getLastKnownPosition().then((value) => setLocation(value));
                    })
                  }
                else
                  {Geolocator.getLastKnownPosition().then((value) => setLocation(value))}
              }
          });
    });
  }

  initialiseHmgServices(bool isLogin) {
    hmgServices.clear();

    hmgServices.add(new HmgServices(0, TranslationBase.of(context).liveCareTitle, TranslationBase.of(context).liveCareSubtitle, "assets/images/new/Live_Care.svg", isLogin));
    hmgServices.add(new HmgServices(1, TranslationBase.of(context).covidTest, TranslationBase.of(context).driveThru, "assets/images/new/CoronaIcon.svg", isLogin));
    hmgServices.add(new HmgServices(2, TranslationBase.of(context).onlinePayment, TranslationBase.of(context).onlinePaymentSubtitle, "assets/images/new/paymentMethods.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).cmcTitle, TranslationBase.of(context).cmcSubtitle, "assets/images/new/comprehensive_checkup.svg", isLogin));
    hmgServices.add(new HmgServices(5, TranslationBase.of(context).emergencyTitle, TranslationBase.of(context).emergencySubtitle, "assets/images/new/emergency.svg", isLogin));
    hmgServices.add(new HmgServices(6, TranslationBase.of(context).ereferralTitle, TranslationBase.of(context).ereferralSubtitle, "assets/images/new/E_Referral.svg", isLogin));
    hmgServices.add(new HmgServices(7, TranslationBase.of(context).waterTitle, TranslationBase.of(context).waterSubtitle, "assets/images/new/h2o.svg", isLogin));
    hmgServices.add(new HmgServices(8, TranslationBase.of(context).connectTitle, TranslationBase.of(context).connectSubtitle, "assets/images/new/reach_us.svg", isLogin));
    hmgServices.add(new HmgServices(9, TranslationBase.of(context).medicalFileTitle2, TranslationBase.of(context).medicalFileSubtitle, "assets/images/new/medical file.svg", isLogin));
    hmgServices.add(new HmgServices(10, TranslationBase.of(context).book, TranslationBase.of(context).appointmentLabel, "assets/images/new/book appointment.svg", isLogin));
    hmgServices.add(new HmgServices(11, TranslationBase.of(context).pharmacyTitle, TranslationBase.of(context).pharmacySubtitle, "assets/images/new/Pharmacy.svg", isLogin));
    hmgServices.add(new HmgServices(12, TranslationBase.of(context).updateInsurance, TranslationBase.of(context).updateInsuranceSubtitle, "assets/images/new/update insurance card.svg", isLogin));
    hmgServices.add(new HmgServices(13, TranslationBase.of(context).familyTitle, TranslationBase.of(context).familySubtitle, "assets/images/new/my family.svg", isLogin));
    hmgServices.add(new HmgServices(14, TranslationBase.of(context).My_Child, TranslationBase.of(context).Vaccines, "assets/images/new/child vaccines.svg", isLogin));
    hmgServices.add(new HmgServices(15, TranslationBase.of(context).Todo, TranslationBase.of(context).list, "assets/images/new/todo.svg", isLogin));
    hmgServices.add(new HmgServices(16, TranslationBase.of(context).Blood, TranslationBase.of(context).Donation, "assets/images/new/blood donation.svg", isLogin));
    hmgServices.add(new HmgServices(17, TranslationBase.of(context).healthCalculatorTitle, TranslationBase.of(context).healthCalculatorSubtitle, "assets/images/new/health calculator.svg", isLogin));
    hmgServices.add(new HmgServices(18, TranslationBase.of(context).healthConvertersTitle, TranslationBase.of(context).healthConvertersSubtitle, "assets/images/new/health converter.svg", isLogin));
    hmgServices.add(new HmgServices(19, TranslationBase.of(context).smartWatches.split(" ")[0], TranslationBase.of(context).smartWatches.split(" ")[1], "assets/images/new/smart watch.svg", isLogin));
    hmgServices.add(new HmgServices(20, TranslationBase.of(context).parkingTitle2, TranslationBase.of(context).parkingSubtitle, "assets/images/new/parking details.svg", isLogin));
    hmgServices.add(new HmgServices(21, TranslationBase.of(context).Virtual, TranslationBase.of(context).Tour, "assets/images/new/virtual tour.svg", isLogin));
    hmgServices.add(new HmgServices(22, TranslationBase.of(context).latestNews.split(" ")[0], TranslationBase.of(context).latestNews.split(" ")[1], "assets/images/new/latest news.svg", isLogin));
  }

  @override
  Widget build(BuildContext context) {
    ProjectViewModel projectViewModel = Provider.of(context);
    initialiseHmgServices(false);
    return AppScaffold(
      isShowAppBar: true,
      isShowDecPage: false,
      showNewAppBar: true,
      showNewAppBarTitle: true,
      appBarTitle: TranslationBase.of(context).hMGService,
      body: Container(
        width: double.infinity,
        height: double.infinity,
        child: SingleChildScrollView(
          child: Column(
            children: [
              Container(
                width: double.infinity,
                decoration: containerRadiusWithGradient(0,
                    color1: timeCalculator(6, 0, 10, 59)
                        ? Color(0xFFB3E3FE)
                        : timeCalculator(11, 0, 15, 59)
                            ? Color(0xFFFF9E7E)
                            : Color(0xFF2E6686),
                    color2: timeCalculator(6, 0, 10, 59)
                        ? Color(0xFF9AC7FF)
                        : timeCalculator(11, 0, 15, 59)
                            ? Color(0xFFFECB50)
                            : Color(0xFF122F48)),
                child: Padding(
                  padding: const EdgeInsets.all(20.0),
                  child: Row(
                    children: [
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Directionality(
                              textDirection: TextDirection.ltr,
                              child: Text(
                                weather,
                                style: TextStyle(
                                  fontSize: 24,
                                  letterSpacing: -0.83,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.white,
                                ),
                              ),
                            ),
                            Text(
                              DateUtil.getMonthDayYearDateFormatted(new DateTime.now()),
                              style: TextStyle(
                                fontSize: 12,
                                letterSpacing: -0.60,
                                fontWeight: FontWeight.w600,
                                color: Colors.white,
                              ),
                            ),
                            Text(
                              TranslationBase.of(context).healthWeatherIndicators,
                              style: TextStyle(
                                fontSize: 12,
                                letterSpacing: -0.96,
                                fontWeight: FontWeight.bold,
                                color: Colors.white,
                              ),
                            ),
                            Text(
                              TranslationBase.of(context).healthTipsBasedOnCurrentWeather,
                              style: TextStyle(
                                fontSize: 10,
                                letterSpacing: -0.72,
                                fontWeight: FontWeight.w600,
                                color: Colors.white,
                              ),
                            ),
                          ],
                        ),
                      ),
                      Column(
                        children: [
                          SvgPicture.asset(
                            "assets/images/new/cloudy.svg",
                          ),
                          InkWell(
                            onTap: () {
                              Navigator.push(
                                context,
                                FadePage(
                                  page: HealthWeatherIndicator(),
                                ),
                              );
                            },
                            child: Padding(
                              padding: const EdgeInsets.only(top: 10, bottom: 0),
                              child: Text(
                                TranslationBase.of(context).moreDetails,
                                style: TextStyle(fontSize: 12, letterSpacing: -0.72, fontWeight: FontWeight.w600, color: Colors.white, decoration: TextDecoration.underline),
                              ),
                            ),
                          )
                        ],
                      ),
                    ],
                  ),
                ),
              ),
              mHeight(16),
              Padding(
                padding: const EdgeInsets.only(
                  left: 16,
                  right: 16,
                  top: 0,
                ),
                child: GridView.builder(
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3, childAspectRatio: 2 / 2, crossAxisSpacing: 12, mainAxisSpacing: 12),
                  physics: NeverScrollableScrollPhysics(),
                  shrinkWrap: true,
                  itemCount: hmgServices.length,
                  padding: EdgeInsets.zero,
                  itemBuilder: (BuildContext context, int index) {
                    return ServicesView(hmgServices[index], index);
                  },
                ),
              ),
              mHeight(16),
            ],
          ),
        ),
      ),
    );
  }

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

  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();
      weatherNum = d.temperature;
      setState(() {
        weather = d != null ? d.temperature.toString() + '\u2103' : '--';
      });
    } else {
      setState(() {
        weather = data != null ? data['Temperature'].toString() + '\u2103' : '--';
      });
    }
  }
}
