import 'package:echo_app/firebase_options.dart';
import 'package:echo_app/models/constant-storage.dart';
import 'package:echo_app/models/time-ago/messages.dart';
import 'package:echo_app/screens/home_page/home.page.dart';
import 'package:echo_app/screens/splash.page.dart';
import 'package:echo_app/screens/tap_page/tap.page.dart';
import 'package:echo_app/services/MyHttpOverrides.dart';
import 'package:echo_app/services/items.service.dart';
import 'package:echo_app/services/localization.service.dart';
import 'package:echo_app/shared/NavigationService.dart';
import 'package:echo_app/shared/core.session.dart';
import 'package:echo_app/theme/variables.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'dart:async';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:timeago/timeago.dart' as timeago;
import 'dart:io';

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  // backgroind and off app
  print('_firebaseMessagingBackgroundHandler');
  await Firebase.initializeApp();

}

Future<void> main() async {
  SystemChrome.setSystemUIOverlayStyle(
    SystemUiOverlayStyle(
        statusBarColor: Variables.color_primary,
        statusBarBrightness: Brightness.dark),
  );
  timeago.setLocaleMessages('ar', Messages());
  timeago.setLocaleMessages('en', Messages());

  CoreSession.init();
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);

  HttpOverrides.global = MyHttpOverrides();

  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}
FirebaseAnalytics analytics = FirebaseAnalytics.instance;
class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  @override
  initState() {
    super.initState();

    WidgetsBinding.instance.addObserver(this);

    FirebaseMessaging.instance.requestPermission();
    FirebaseMessaging.instance.getInitialMessage().then((message) {
      // not used until now
      print('FirebaseMessaging.instance.getInitialMessage');
      if (message != null) {}
    });
    analytics.setAnalyticsCollectionEnabled(true);

    FirebaseMessaging.onMessage.listen((message) {
      // foreground notifications
      print('FirebaseMessaging.onMessage.listen');
      if (message != null && message.data != null) {
        CoreSession.newNotificationCount = int.parse(message.data['badge']);
      }
      TapPage.enteredValue.value = CoreSession.newNotificationCount;
      HomePage.ReloadHome();
    });

    FirebaseMessaging.onMessageOpenedApp.listen((message) {
      // on click on  pop up notification
      print('FirebaseMessaging.onMessageOpenedApp.listen');
      navigateToNextPage();
    });
  }

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

  @override
  Future<void> didChangeAppLifecycleState(AppLifecycleState state) async {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.paused) {
      print("paused");

      // ignore: non_constant_identifier_names
      ItemService _ItemService = new ItemService();
      var responce = await _ItemService.saveCustomerBasket(CoreSession.currentBasket['items']);
      print("paused2");
      print(responce);
    }
  }

  void navigateToNextPage() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? token = prefs.getString(ConstantStorage.tokenName);
    if (token != null && token != '') {
      // setState(() {
      // Navigator.pushNamed(context, '/NotificationPage');
      // Navigator.push(
      //   context,
      //   MaterialPageRoute(
      //     builder: (context) => NotificationPage(),
      //   ),
      // );
      // });
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
            theme: ThemeData(
        primaryColor: Variables.color_primary,
        fontFamily: 'Poppins',
        textTheme: TextTheme(
          headlineLarge: TextStyle(
            fontFamily: 'Poppins',
            color: Colors.grey.shade800,
            fontWeight: FontWeight.bold,
            fontSize: Variables.headline1FontSize,
          ),
          headlineMedium: TextStyle(
            fontFamily: 'Poppins',
            color: Colors.grey.shade800,
            fontWeight: FontWeight.bold,
            fontSize: Variables.headline2FontSize,
          ),
        bodyMedium: TextStyle(
            fontFamily: 'Poppins',
            color: Colors.grey.shade800,
            fontWeight: FontWeight.bold,
            fontSize: Variables.headline2FontSize,
          ),
         headlineSmall: TextStyle(
            fontFamily: 'Poppins',
            color: Colors.grey.shade800,
            fontWeight: FontWeight.normal,
            fontSize: Variables.headline5FontSize,
          ),
        ),
        appBarTheme: AppBarTheme(
          iconTheme: IconThemeData(color: Colors.white),
          color: Variables.color_primary, //<-- SEE HERE
          
        ),
        primaryColorLight:  Variables.color_primary,
        primaryColorDark: Variables.color_primary,
        
      ),
      navigatorKey: NavigationService.navigatorKey,

      debugShowCheckedModeBanner: false,
      title: 'Echo Demo',
      home: MyHomePage(),
    );
  }
}

// ignore: must_be_immutable
class MyHomePage extends StatelessWidget {
  MyHomePage() {
    CoreSession.setLanguage();
    //_coreSession.initializeApp();
  }

  @override
  Widget build(BuildContext context) {
    Variables.getMediaQuery(context);
    return GetMaterialApp(
      //theme: ThemeData(primarySwatch: Colors.green), home: LoginPage()
      title: '',
      debugShowCheckedModeBanner: false,
      translations: LocalizationService(),
      locale: CoreSession.locale,
      builder: EasyLoading.init(),
      fallbackLocale: CoreSession.locale,

      home: SafeArea(child: SplashPage()),
    );
  }
}
