import 'dart:io';
import 'dart:typed_data';

import 'package:diplomaticquarterapp/config/config.dart';
import 'package:diplomaticquarterapp/config/shared_pref_kay.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/ToDoList/ToDo.dart';
import 'package:diplomaticquarterapp/pages/livecare/incoming_call.dart';
import 'package:diplomaticquarterapp/pages/medical/medical_profile_page.dart';
import 'package:diplomaticquarterapp/pages/medical/my_admissions_page.dart';
import 'package:diplomaticquarterapp/services/authentication/auth_provider.dart';
import 'package:diplomaticquarterapp/uitl/CalendarUtils.dart';
import 'package:diplomaticquarterapp/uitl/LocalNotification.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/bottom_navigation/bottom_nav_bar.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:rxdart/rxdart.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 {
  int currentTab = 0;
  PageController pageController;
  ProjectViewModel projectProvider;
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
  final authService = new AuthProvider();

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

  _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);

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

    _firebaseMessaging.getToken().then((String token) {
      sharedPref.setString(PUSH_TOKEN, token);
      if (token != null) {
        checkUserStatus(token);
      }
      requestPermissions();
    }).catchError((err) {
      print(err);
    });

    //_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);
  }

  void requestPermissions() async {
    await [
      Permission.location,
      Permission.storage,
      Permission.camera,
      Permission.photos,
      Permission.notification,
      Permission.accessMediaLocation,
      Permission.calendar,
    ].request();

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

  }

  Future<void> _scheduleNotification() async {
    var scheduledNotificationDateTime =
    DateTime.now().add(Duration(seconds: 5));
    var vibrationPattern = Int64List(4);
    vibrationPattern[0] = 0;
    vibrationPattern[1] = 1000;
    vibrationPattern[2] = 5000;
    vibrationPattern[3] = 2000;

    var androidPlatformChannelSpecifics = AndroidNotificationDetails(
        'your other channel id',
        'your other channel name',
        'your other channel description',
       // icon: 'secondary_icon',
        sound: RawResourceAndroidNotificationSound('slow_spring_board'),
        largeIcon: DrawableResourceAndroidBitmap('sample_large_icon'),
        vibrationPattern: vibrationPattern,
        enableLights: true,
        color: const Color.fromARGB(255, 255, 0, 0),
        ledColor: const Color.fromARGB(255, 255, 0, 0),
        ledOnMs: 1000,
        ledOffMs: 500);
    var iOSPlatformChannelSpecifics =
    IOSNotificationDetails(sound: 'slow_spring_board.aiff');
    var platformChannelSpecifics = NotificationDetails(
        androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
    await flutterLocalNotificationsPlugin.schedule(
        0,
        'scheduled title',
        'scheduled body',
        scheduledNotificationDateTime,
        platformChannelSpecifics);
  }


  @override
  Widget build(BuildContext context) {
    //final searchValue = Provider.of<SearchProvider>(context);
    //print(searchValue);
    // projectProvider = Provider.of(context);
    // checkValue(projectProvider);
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        textTheme: TextTheme(
          headline6:
              TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
        ),
        title: Text(getText(currentTab).toUpperCase()),
        leading: Builder(
          builder: (BuildContext context) {
            return IconButton(
              icon: Icon(Icons.menu),
              color: Colors.white,
              onPressed: () => Scaffold.of(context).openDrawer(),
            );
          },
        ),
        centerTitle: true,
      ),
      drawer: SafeArea(child: AppDrawer()),
      extendBody: true,
      body: PageView(
        physics: NeverScrollableScrollPhysics(),
        controller: pageController,
        children: [
          HomePage(
            goToMyProfile: () {
              _changeCurrentTab(1);
            },
          ),
          MedicalProfilePage(),
          MyAdmissionsPage(),
          ToDo(),
          BookingOptions()
        ], // Please do not remove the BookingOptions from this array
      ),
      bottomNavigationBar: BottomNavBar(
        changeIndex: _changeCurrentTab,
        index: currentTab,
      ),
    );
  }

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

  void checkUserStatus(token) async {
    authService
        .selectDeviceImei(token)
        .then((SelectDeviceIMEIRES value) => setUserValues(value));
    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);
      // setState(() {
      //   this.user = data;
      //   print(this.user);
      // });
    }
  }

  static Future<dynamic> myBackgroundMessageHandler(
      Map<String, dynamic> message) async {
    Map<String, dynamic> myMap = new Map<String, dynamic>.from(message['data']);
    print(myMap);

    print("myBackgroundMessageHandler Out");
    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 {
    sharedPref.setObject(IMEI_USER_DATA, value);
  }

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