import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:plataforma_educativa/src/bloc/provider.dart';
import 'package:plataforma_educativa/src/pages/error_page.dart';
import 'package:plataforma_educativa/src/pages/home_page.dart';
import 'package:plataforma_educativa/src/pages/load_page.dart';
import 'package:plataforma_educativa/src/pages/login_page.dart';
import 'package:plataforma_educativa/src/pages/menu_page.dart';
import 'package:plataforma_educativa/src/providers/db_provider.dart';
import 'package:workmanager/workmanager.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

void callbackDispatcher(){
  Workmanager().executeTask((taskName, inputData) async{
    FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
    const AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings('app_icon');
    const InitializationSettings initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid
    );
    await flutterLocalNotificationsPlugin.initialize(initializationSettings, onSelectNotification: onSelectNotification);

    const AndroidNotificationDetails androidNotificationDetails = AndroidNotificationDetails("plataformaEdu", "PlatEdu",
      channelDescription: "Prueba",
      importance: Importance.max,
      priority: Priority.high,
      ticker: 'ticker'
    );

    const NotificationDetails notificationDetails = NotificationDetails(
      android: androidNotificationDetails
    );

    await flutterLocalNotificationsPlugin.show(0, "Prueba", "Texto ejemplo", notificationDetails);
    return Future.value(true);
  });
}

void onSelectNotification(String? payload) async{
  // ignore: avoid_print
  print("PRUEBA");
}

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  Workmanager().initialize(callbackDispatcher, isInDebugMode: true);
  Workmanager().registerPeriodicTask("2", "periodic", frequency: const Duration(minutes: 15));
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

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

class _MyAppState extends State<MyApp> {
  final GlobalKey<NavigatorState> _navKey = GlobalKey<NavigatorState>();

  late FirebaseMessaging _messaging;
  late String _tokenFCM;

  bool _error = false;
  String _strError = "";

  Future<void> initializeFlutterFire() async{
    try{
      await Firebase.initializeApp();
      setState(() => _strError = "");
    }catch(e){
      _error = true;
      _strError = e.toString();
    }
  }

  Future<void> requestPermission() async{
    NotificationSettings settings = await _messaging.requestPermission(
      alert: true,
      announcement: false,
      badge: true,
      carPlay: false,
      criticalAlert: false,
      provisional: false,
      sound: true,
    );
  }

  Future<String> getFCMToken() async{
    String? token = await _messaging.getToken();
    return token!;
  }

  @override
  void initState() {
    super.initState();
    initializeFlutterFire().then((value){
      if(_error){
        _navKey.currentState!.pushReplacement(MaterialPageRoute(
          builder: (context) =>ErrorPage(strError: _strError)
        ));
      }else{
        _messaging = FirebaseMessaging.instance;
        requestPermission();
        getFCMToken().then((token){
          setState(() {
            _tokenFCM = token;

            FirebaseMessaging.onMessage.listen((message) {
              // ignore: avoid_print
              print('Got a message whilst in the foreground!');
              // ignore: avoid_print
              print('Message data: ${message.data}');
            });

            DBProvider.db.getAllUsers().then((users){
              if(users.isNotEmpty){
                const mes = 30 * 24 * 60;
                const dia = 24 * 60;
                final dif = DateTime.now().difference(users.first.until).inMinutes;
                if(users.first.active && dif <= mes){
                  print("SESION MENSUAL");
                }else{
                  if(dif <= dia && users.first.tipoUsuario != "PF"){
                    _navKey.currentState!.pushReplacement(MaterialPageRoute(
                      builder: (context) => MenuPage(
                        esPadre: false,
                        revisaHijo: false,
                        fcmToken: _tokenFCM,
                      ),
                    ));
                  }else if(dif <= dia && users.first.tipoUsuario == "PF"){
                    _navKey.currentState!.pushReplacement(MaterialPageRoute(
                      builder: (context) => HomePage(fcmToken: _tokenFCM),
                    ));
                  }else{
                    _navKey.currentState!.pushReplacement(MaterialPageRoute(
                      builder: (context) => LoginPage(
                        fcmToken: _tokenFCM,
                        rememberSession: false,
                      ),
                    ));
                  }
                }
              }else{
                _navKey.currentState!.pushReplacement(MaterialPageRoute(
                  builder: (context) => LoginPage(
                    fcmToken: _tokenFCM,
                    rememberSession: false,
                  )
                ));
              }
            });
          });
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Provider(
      child: MaterialApp(
        navigatorKey: _navKey,
        debugShowCheckedModeBanner: false,
        title: "Plataforma Educativa",
        home: const LoadPage(),
        localizationsDelegates: const [
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
        ],
        supportedLocales: const [
          Locale('en'),
          Locale('es'),
        ],
        locale: const Locale('es'),
      ),
    );
  }
}

