import 'dart:io';

import 'package:diplomaticquarterapp/config/config.dart';
import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/model/geofencing/requests/GeoZonesRequestModel.dart';
import 'package:diplomaticquarterapp/core/service/AuthenticatedUserObject.dart';
import 'package:diplomaticquarterapp/core/service/geofencing/GeofencingServices.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.dart';
import 'package:diplomaticquarterapp/models/Authentication/select_device_imei_res.dart';
import 'package:diplomaticquarterapp/models/LiveCare/IncomingCallData.dart';
import 'package:diplomaticquarterapp/pages/BookAppointment/BookingOptions.dart';
import 'package:diplomaticquarterapp/pages/DrawerPages/family/my-family.dart';
import 'package:diplomaticquarterapp/pages/ToDoList/ToDo.dart';
import 'package:diplomaticquarterapp/pages/livecare/incoming_call.dart';
import 'package:diplomaticquarterapp/pages/medical/medical_profile_page.dart';
import 'package:diplomaticquarterapp/services/authentication/auth_provider.dart';
import 'package:diplomaticquarterapp/services/family_files/family_files_provider.dart'
    as family;
import 'package:diplomaticquarterapp/services/robo_search/event_provider.dart';
import 'package:diplomaticquarterapp/uitl/CalendarUtils.dart';
import 'package:diplomaticquarterapp/uitl/HMGNetworkConnectivity.dart';
import 'package:diplomaticquarterapp/uitl/HMG_Geofence.dart';
import 'package:diplomaticquarterapp/uitl/LocalNotification.dart';
import 'package:diplomaticquarterapp/uitl/PlatformBridge.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/uitl/location_util.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/bottom_navigation/bottom_nav_bar.dart';
import 'package:diplomaticquarterapp/widgets/buttons/floatingActionButton.dart';
import 'package:diplomaticquarterapp/widgets/data_display/text.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/confirm_dialog.dart';
import 'package:diplomaticquarterapp/widgets/drawer/app_drawer_widget.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
import '../../locator.dart';
import '../../routes.dart';
import 'home_page.dart';

class LandingPage extends StatefulWidget {
  static bool isOpenCallPage = false;

  static IncomingCallData incomingCallData = new IncomingCallData();

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

class _LandingPageState extends State<LandingPage> with WidgetsBindingObserver {
  var authProvider = new AuthProvider();

  int currentTab = 0;
  PageController pageController;
  ProjectViewModel projectViewModel;
  var notificationCount = '';
  var themeNotifier;

  ///inject the user data
  AuthenticatedUserObject authenticatedUserObject = locator<
      AuthenticatedUserObject>();

  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
  final authService = new AuthProvider();
  var event = RobotProvider();
  var familyFileProvider = family.FamilyFilesProvider();

  void _requestIOSPermissions() {
    flutterLocalNotificationsPlugin
        .resolvePlatformSpecificImplementation<
        IOSFlutterLocalNotificationsPlugin>()
        ?.requestPermissions(
      alert: true,
      badge: true,
      sound: true,
    );
  }

  bool isPageNavigated = false;
  LocationUtils locationUtils;

  _changeCurrentTab(int tab) {
    setState(() {
      currentTab = tab;
      pageController.jumpToPage(tab);
    });
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);

    var route = ModalRoute.of(context);

    if (route != null) {
      print(route.settings.name);
    }

    //setState(() {
    print("didChangeAppLifecycleState");
    print('state = $state');
    AppGlobal.context = context;
    if (state == AppLifecycleState.resumed) {
      print(LandingPage.isOpenCallPage);
      if (LandingPage.isOpenCallPage) {
        if (!isPageNavigated) {
          isPageNavigated = true;
          Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) =>
                      IncomingCall(
                          incomingCallData: LandingPage.incomingCallData)))
              .then((value) {
            isPageNavigated = false;
          });
        }
      }
    }

    if (state == AppLifecycleState.paused) {
      isPageNavigated = false;
    }

    if (state == AppLifecycleState.inactive) {
      isPageNavigated = false;
    }
    //});
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    //setState(() {
    AppGlobal.context = context;
    // });
    _requestIOSPermissions();
    pageController = PageController(keepPage: true);
    _firebaseMessaging.setAutoInitEnabled(true);

    // HMG (Guest/Internet) Wifi Access [Zohaib Kambrani]
    HMGNetworkConnectivity(context, () {
      GifLoaderDialogUtils.showMyDialog(context);
      PlatformBridge().connectHMGGuestWifi().then((value) =>
      {
        GifLoaderDialogUtils.hideDialog(context)
      });
    }).checkAndConnectIfNoInternet();


    if (Platform.isIOS) {
      _firebaseMessaging.requestNotificationPermissions();
    }

    requestPermissions().then((results) {
      registerGeofences();

      if (results[Permission.notification].isGranted)
        _firebaseMessaging.getToken().then((String token) {
          sharedPref.setString(PUSH_TOKEN, token);
          if (token != null && DEVICE_TOKEN == "") {
            DEVICE_TOKEN = token;
            checkUserStatus(token);
          }
        });
      if (results[Permission.location].isGranted);
      if (results[Permission.storage].isGranted);
      if (results[Permission.camera].isGranted);
      if (results[Permission.photos].isGranted);
      if (results[Permission.accessMediaLocation].isGranted);
      if (results[Permission.calendar].isGranted);
    });
    requestPermissions();
    // });
    //
    // //_firebase Background message handler
    // _firebaseMessaging.configure(
    //     //   onMessage: (Map<String, dynamic> message) async {
    //     //     showDialog("onMessage: $message");
    //     //     print("onMessage: $message");
    //     //     print(message);
    //     //     print(message['name']);
    //     //     print(message['appointmentdate']);
    //     //
    //     //     if (Platform.isIOS) {
    //     //       if (message['is_call'] == "true") {
    //     //         var route = ModalRoute.of(context);
    //     //
    //     //         if (route != null) {
    //     //           print(route.settings.name);
    //     //         }
    //     //
    //     //         Map<String, dynamic> myMap = new Map<String, dynamic>.from(message);
    //     //         print(myMap);
    //     //         LandingPage.isOpenCallPage = true;
    //     //         LandingPage.incomingCallData = IncomingCallData.fromJson(myMap);
    //     //         if (!isPageNavigated) {
    //     //           isPageNavigated = true;
    //     //           Navigator.push(
    //     //                   context,
    //     //                   MaterialPageRoute(
    //     //                       builder: (context) => IncomingCall(
    //     //                           incomingCallData: LandingPage.incomingCallData)))
    //     //               .then((value) {
    //     //             isPageNavigated = false;
    //     //           });
    //     //         }
    //     //       } else {
    //     //         print("Is Call Not Found iOS");
    //     //       }
    //     //     } else {
    //     //       print("Is Call Not Found iOS");
    //     //     }
    //     //
    //     //     if (Platform.isAndroid) {
    //     //       if (message['data'].containsKey("is_call")) {
    //     //         var route = ModalRoute.of(context);
    //     //
    //     //         if (route != null) {
    //     //           print(route.settings.name);
    //     //         }
    //     //
    //     //         Map<String, dynamic> myMap =
    //     //             new Map<String, dynamic>.from(message['data']);
    //     //         print(myMap);
    //     //         LandingPage.isOpenCallPage = true;
    //     //         LandingPage.incomingCallData = IncomingCallData.fromJson(myMap);
    //     //         if (!isPageNavigated) {
    //     //           isPageNavigated = true;
    //     //           Navigator.push(
    //     //                   context,
    //     //                   MaterialPageRoute(
    //     //                       builder: (context) => IncomingCall(
    //     //                           incomingCallData: LandingPage.incomingCallData)))
    //     //               .then((value) {
    //     //             isPageNavigated = false;
    //     //           });
    //     //         }
    //     //       } else {
    //     //         print("Is Call Not Found Android");
    //     //       }
    //     //     } else {
    //     //       print("Is Call Not Found Android");
    //     //     }
    //     //   },
    //     //   onBackgroundMessage: Platform.isIOS ? null : myBackgroundMessageHandler,
    //     //   onLaunch: (Map<String, dynamic> message) async {
    //     //     print("onLaunch: $message");
    //     //     showDialog("onLaunch: $message");
    //     //   },
    //     //   onResume: (Map<String, dynamic> message) async {
    //     //     print("onResume: $message");
    //     //     print(message);
    //     //     print(message['name']);
    //     //     print(message['appointmentdate']);
    //     //
    //     //     showDialog("onResume: $message");
    //     //
    //     //     if (Platform.isIOS) {
    //     //       if (message['is_call'] == "true") {
    //     //         var route = ModalRoute.of(context);
    //     //
    //     //         if (route != null) {
    //     //           print(route.settings.name);
    //     //         }
    //     //
    //     //         Map<String, dynamic> myMap =
    //     //         new Map<String, dynamic>.from(message);
    //     //         print(myMap);
    //     //         LandingPage.isOpenCallPage = true;
    //     //         LandingPage.incomingCallData = IncomingCallData.fromJson(myMap);
    //     //         if (!isPageNavigated) {
    //     //           isPageNavigated = true;
    //     //           Navigator.push(
    //     //               context,
    //     //               MaterialPageRoute(
    //     //                   builder: (context) => IncomingCall(
    //     //                       incomingCallData: LandingPage.incomingCallData)))
    //     //               .then((value) {
    //     //             isPageNavigated = false;
    //     //           });
    //     //         }
    //     //       } else {
    //     //         print("Is Call Not Found iOS");
    //     //       }
    //     //     } else {
    //     //       print("Is Call Not Found iOS");
    //     //     }
    //     //   },
    //     );
  }

  showDialogs(String message) {
    ConfirmDialog dialog = new ConfirmDialog(
        context: context,
        confirmMessage: message,
        okText: TranslationBase
            .of(context)
            .confirm,
        cancelText: TranslationBase
            .of(context)
            .cancel_nocaps,
        okFunction: () => {},
        cancelFunction: () => {});
    dialog.showAlertDialog(context);
  }

  Future<Map<Permission, PermissionStatus>> requestPermissions() async {
    var permissionResults = [
      Permission.location,
      Permission.locationAlways,
      Permission.storage,
      Permission.camera,
      Permission.photos,
      Permission.notification,
      Permission.accessMediaLocation,
      Permission.calendar,
      Permission.activityRecognition
    ].request();

    var permissionsGranted = await deviceCalendarPlugin.hasPermissions();
    if (permissionsGranted.isSuccess && !permissionsGranted.data) {
      permissionsGranted = await deviceCalendarPlugin.requestPermissions();
      if (!permissionsGranted.isSuccess || !permissionsGranted.data) {}
    }
    return permissionResults;
  }

  setTheme() async {
    //
    // defaultTheme =
    //    ThemeData(
    //    fontFamily:projectViewModel.isArabic ? 'Cairo' :  'WorkSans',
    //    primarySwatch: Colors.blue,
    //    visualDensity: VisualDensity.adaptivePlatformDensity,
    //    brightness: Brightness.light,
    //    pageTransitionsTheme: const PageTransitionsTheme(
    //      builders: {
    //        TargetPlatform.android: ZoomPageTransitionsBuilder(),
    //        TargetPlatform.iOS: CupertinoPageTransitionsBuilder(),
    //      },
    //    ),
    //    hintColor: Colors.grey[400],
    //    disabledColor: Colors.grey[300],
    //    errorColor: Color.fromRGBO(235, 80, 60, 1.0),
    //    scaffoldBackgroundColor: Color(0xffEEEEEE),
    //    textSelectionColor: Color.fromRGBO(80, 100, 253, 0.5),
    //    textSelectionHandleColor: Colors.grey,
    //    canvasColor: Colors.white,
    //    backgroundColor: Colors.white,
    //    highlightColor: Colors.grey[100].withOpacity(0.4),
    //    splashColor: Colors.transparent,
    //    primaryColor: Color(0xff40ACC9),
    //    bottomSheetTheme: BottomSheetThemeData(backgroundColor: Color(0xffE0E0E0)),
    //    cursorColor: Colors.grey,
    //    cardColor: Colors.white,
    //    iconTheme: IconThemeData(),
    //    appBarTheme: AppBarTheme(
    //      color: Color(0xff40ACC9),
    //      brightness: Brightness.dark,
    //      elevation: 10.0,
    //      actionsIconTheme: IconThemeData(
    //        color: Color(0xff40ACC9),
    //      ),
    //    ),
    //  );
    // themeNotifier.setTheme(defaultTheme);
  }

  static Future<dynamic> myBackgroundMessageHandler(
      Map<String, dynamic> message) async {
    Map<String, dynamic> myMap = new Map<String, dynamic>.from(message['data']);
    if (message.containsKey('data')) {
      print("myBackgroundMessageHandler Inside");
      LandingPage.incomingCallData = IncomingCallData.fromJson(myMap);
      print(LandingPage.incomingCallData.doctorname);
      LandingPage.isOpenCallPage = true;
    }

    if (message.containsKey('notification')) {
      final dynamic notification = message['notification'];
      print(notification);
    }
  }

  void setUserValues(value) async {
    if (value != null) sharedPref.setObject(IMEI_USER_DATA, value);
  }

  Future<dynamic> getUserInformation() async {
    var userInfoJson = sharedPref.getObject(IMEI_USER_DATA);
    return userInfoJson;
  }

  checkValue(projectProvider) {
    if (projectProvider.searchValue != null) {
      _changeCurrentTab(2);
    }
  }

  registerGeofences() async {
    await locator<GeofencingServices>().getAllGeoZones(GeoZonesRequestModel());

    void doIt() {
      getUserInformation().then((value) {
        if (value != null) projectViewModel.platformBridge()
            .registerHmgGeofences();
      });
    }

    if (await Permission.location.isGranted) {
      doIt();
    } else {
      [Permission.location].request().then((value) async {
        if (await Permission.location.isGranted) {
          doIt();
        }
      });
    }

  }

  login() async {
    var data = await sharedPref.getObject(IMEI_USER_DATA);
    sharedPref.remove(REGISTER_DATA_FOR_LOGIIN);
    if (data != null) {
      Navigator.of(context).pushNamed(CONFIRM_LOGIN);
    } else {
      GifLoaderDialogUtils.showMyDialog(context);
      authService
          .selectDeviceImei(DEVICE_TOKEN)
          .then((SelectDeviceIMEIRES value) {
        GifLoaderDialogUtils.hideDialog(context);
        if (value != null) {
          setUserValues(value);
          Navigator.of(context).pushNamed(CONFIRM_LOGIN);
        } else {
          Navigator.of(context).pushNamed(
            WELCOME_LOGIN,
          );
        }
      }).catchError((err) {
        GifLoaderDialogUtils.hideDialog(context);
        Navigator.of(context).pushNamed(
          WELCOME_LOGIN,
        );
      });
    }
  }

  getNotificationCount(token) async {
    if (await sharedPref.getObject(USER_PROFILE) != null) {
      var data =
      AuthenticatedUser.fromJson(await sharedPref.getObject(USER_PROFILE));
      if (data != null) {
        authService
            .registeredAuthenticatedUser(data, token, 0, 0)
            .then((res) => {print(res)});
        authService.getDashboard().then((value) =>
        {
          setState(() {
            notificationCount = value['List_PatientDashboard'][0]
            ['UnreadPatientNotificationCount'] >
                99
                ? '99+'
                : value['List_PatientDashboard'][0]
            ['UnreadPatientNotificationCount']
                .toString();

            sharedPref.setString(NOTIFICATION_COUNT, notificationCount);
          })
        });
        familyFileProvider.getSharedRecordByStatus();
      }
    }
  }


  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);

    return Scaffold(
        appBar: AppBar(
          elevation: 0,
          textTheme: TextTheme(
            headline6: TextStyle(
                color: Colors.white, fontWeight: FontWeight.bold),
          ),
          title: Text(
            getText(currentTab).toUpperCase(),
            style: TextStyle(
                fontWeight: FontWeight.bold,
                color: Colors.white,
                fontFamily: projectViewModel.isArabic ? 'Cairo' : 'WorkSans'),
            // bold: true,
            // color: Colors.white,
          ),
          leading: Builder(
            builder: (BuildContext context) {
              return new Stack(
                children: <Widget>[
                  IconButton(
                    icon: Icon(Icons.menu),
                    color: Colors.white,
                    onPressed: () => Scaffold.of(context).openDrawer(),
                  ),
                  notificationCount != ''
                      ? new Positioned(
                    right: projectViewModel.isArabic ? 35 : 0,
                    top: 5,
                    child: new Container(
                      padding: EdgeInsets.all(4),
                      decoration: new BoxDecoration(
                        color: Colors.red,
                        borderRadius: BorderRadius.circular(20),
                      ),
                      constraints: BoxConstraints(
                        minWidth: 20,
                        minHeight: 20,
                      ),
                      child: new Text(
                        notificationCount,
                        style: new TextStyle(
                          color: Colors.white,
                          fontSize: projectViewModel.isArabic ? 8 : 9,
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  )
                      : SizedBox()
                ],
              );
            },
          ),
          actions: [
            IconButton(
              //iconSize: 70,
              icon: Icon(
                projectViewModel.isLogin ? Icons.settings : Icons.login,
                color: Colors.white,
              ),
              onPressed: () {
                if (projectViewModel.isLogin)
                  Navigator.of(context).pushNamed(
                    SETTINGS,
                  );
                else
                  login();
              }, //do something,
            )
          ],
          centerTitle: true,
        ),
        drawer: SafeArea(child: AppDrawer()),
        extendBody: true,
        body: PageView(
          physics: NeverScrollableScrollPhysics(),
          controller: pageController,
          children: [
            HomePage(
              goToMyProfile: () {
                _changeCurrentTab(1);
              },
            ),
            MedicalProfilePage(),
            BookingOptions(),
            MyFamily(isAppbarVisible: false),
            ToDo(isShowAppBar: false),
          ], // Please do not remove the BookingOptions from this array
        ),
        bottomNavigationBar: BottomNavBar(
          changeIndex: _changeCurrentTab,
          index: currentTab,
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        floatingActionButton: currentTab == 0
            ? FloatingButton(
            elevation: true,
            onTap: () {
              _changeCurrentTab(2);
            })
            : null);
  }

  triggerRobot() {
    event.setValue({"isRobot": 'true'});
  }

  getText(currentTab) {
    switch (currentTab) {
      case 0:
        return TranslationBase.of(context).home;
      case 1:
        return TranslationBase.of(context).medicalProfile;
      case 2:
        return TranslationBase.of(context).bookAppo;
        case 5:
        return TranslationBase.of(context).bookAppo;
      case 3:
        return TranslationBase.of(context).services;
      case 4:
        return TranslationBase.of(context).bookAppo;
    }
  }

  void checkUserStatus(token, {isLoader = true}) async {
    if (isLoader)
      //GifLoaderDialogUtils.showMyDialog(context);
      authService
          .selectDeviceImei(token)
          .then((SelectDeviceIMEIRES value) => setUserValues(value))
          .catchError((err) {
        //GifLoaderDialogUtils.hideDialog(context);
      });

    // if (await sharedPref.getObject(USER_PROFILE) != null) {
    //   var data = AuthenticatedUser.fromJson(await sharedPref.getObject(USER_PROFILE));
    //   if (data != null) {
    //     authService.registeredAuthenticatedUser(data, token, 0, 0).then((res) => {print(res)});
    //     authService.getDashboard().then((value) => {
    //       setState(() {
    //         notificationCount = value['List_PatientDashboard'][0]['UnreadPatientNotificationCount'].toString();
    //       })
    //     });
    //   }
    // }
  }

}
