import 'dart:convert';

import 'package:boilerplate/core/di/injection_init.dart';
import 'package:boilerplate/core/utils/navigator_util.dart';
import 'package:boilerplate/core/utils/print_utils.dart';
import 'package:boilerplate/core/utils/shared_preferences_util.dart';
import 'package:boilerplate/presentation/bloc/notification/notification_count/notification_count_cubit.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_badger/flutter_app_badger.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

import '../../presentation/screen/notification/notifications_screen.dart';
import 'authentication_util.dart';

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  print('Handling a background message ${message.messageId}');

  await FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
    RemoteNotification? notification = message.notification;
    AndroidNotification? android = message.notification?.android;
    if (notification != null && android != null) {
      flutterLocalNotificationsPlugin.show(
          notification.hashCode,
          notification.title,
          notification.body,
          NotificationDetails(
            android: AndroidNotificationDetails(
              channel.id,
              channel.name,
              color: Colors.blue,
              playSound: true,
              icon: '@mipmap/ic_launcher',
            ),
          ));
    }
  });
  NotificationUtil.countNotification();
}

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

/// Create a [AndroidNotificationChannel] for heads up notifications
const AndroidNotificationChannel channel = AndroidNotificationChannel(
  'high_importance_channel', // id
  'High Importance Notifications', // title
  importance: Importance.max,
  enableVibration: true,
  playSound: true, showBadge: true,
);

class NotificationUtil {
  static final FirebaseMessaging _messaging = FirebaseMessaging.instance;
  static final flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();

  static initial() async {
    await Firebase.initializeApp();
    final fcmToken = await FirebaseMessaging.instance.getToken();
    print("fcmToken = ${fcmToken}");

    NotificationSettings settings = await _messaging.requestPermission(
      alert: true,
      badge: true,
      sound: true,
    );

    await FirebaseMessaging.instance
        .setForegroundNotificationPresentationOptions(
      alert: true,
      badge: true,
      sound: true,
    );
    if (settings.authorizationStatus == AuthorizationStatus.authorized) {
      await FirebaseMessaging.instance
          .setForegroundNotificationPresentationOptions(
        alert: true,
        badge: true,
        sound: true,
      );
    }
    await FlutterAppBadger.isAppBadgeSupported();

    //#region init local push notification
    await flutterLocalNotificationsPlugin.initialize(
      InitializationSettings(
        android: AndroidInitializationSettings('ic_launcher'),
        iOS: DarwinInitializationSettings(
          requestAlertPermission: true,
          requestBadgePermission: true,
          requestSoundPermission: true,
        ),
      ),
    );
    await FirebaseMessaging.instance.getInitialMessage().then((message) async {
      if (message != null) {
        // DO YOUR THING HERE
        await countNotification();
      }
    });
    //#endregion
    await FirebaseMessaging.onMessageOpenedApp
        .listen((RemoteMessage message) async {
      print(
          'A new messageopen app event was published ${message.notification!.body}');
      // final pref = getIt.get<SharedPreferencesUtil>();
      //
      // pref.putInt(SharedPreferencesUtil.keyNotificationCount, 0);
      //
      // FlutterAppBadger.removeBadge();
      // FlutterAppBadger.updateBadgeCount(0);

      print('A new messageopen app event was published ${message.data}');
      RemoteNotification? notification = message!.notification;
      AndroidNotification? android = message.notification!.android;

      final body = json.decode(message.notification!.body.toString());
      print(body);
      print(body['type']);
      print(body['url']);

      if (notification != null && android != null) {
        // print(message.data['type']);
        // await updateBadge();
        await countNotification();
      }
      // if (NavigatorUtil.navigate.currentState != null) {
      //   BlocProvider.of<NotificationCountCubit>(
      //           NavigatorUtil.navigate.currentState!.context)
      //       .clearNotificationCount();
      // }
      // FlutterAppBadger.removeBadge();
    });
    FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
    FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
      print('onMessage : ${message.data}');

      RemoteNotification? notification = message.notification;
      AndroidNotification? android = message.notification?.android;
      if (notification != null && android != null) {
        flutterLocalNotificationsPlugin.show(
            notification.hashCode,
            notification.title,
            notification.body,
            NotificationDetails(
              android: AndroidNotificationDetails(
                channel.id,
                channel.name,
                color: Colors.blue,
                playSound: true,
                icon: '@mipmap/ic_launcher',
              ),
            ));
      }
      await countNotification();

      // final title = message.notification?.title ?? '';
      // final body = message.notification?.body ?? '';
      // final payload = jsonEncode(message.data);
      //
      // _showNotification(title, body, payload);
    });

    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage? message) async {
      print('onOpenApp : ${message?.data}');
      // countNotification();
      // final pref = getIt.get<SharedPreferencesUtil>();
      //
      // pref.putInt(SharedPreferencesUtil.keyNotificationCount, 0);
      //
      // FlutterAppBadger.removeBadge();
      // FlutterAppBadger.updateBadgeCount(0);
      // if (NavigatorUtil.navigate.currentState != null) {
      //   BlocProvider.of<NotificationCountCubit>(
      //           NavigatorUtil.navigate.currentState!.context)
      //       .clearNotificationCount();
      // }
      // FlutterAppBadger.removeBadge();
      await countNotification();

      await AuthenticationUtil.checkHasUser(() {
        NavigatorUtil.pushToPage(NotificationsScreen());
      });
    });
  }

  static countNotification() {
    final pref = getIt.get<SharedPreferencesUtil>();
    int count;
    if (pref.getInt(SharedPreferencesUtil.keyNotificationCount) == 0 ||
        pref.getInt(SharedPreferencesUtil.keyNotificationCount) == null) {
      count = 1;
      pref.putInt(SharedPreferencesUtil.keyNotificationCount, count);
      if (NavigatorUtil.navigate.currentState != null) {
        BlocProvider.of<NotificationCountCubit>(
                NavigatorUtil.navigate.currentState!.context)
            .getNotificationCount();
      }
      FlutterAppBadger.updateBadgeCount(count);
    } else {
      count = pref.getInt(SharedPreferencesUtil.keyNotificationCount)!;
      pref.putInt(SharedPreferencesUtil.keyNotificationCount, count++);
      if (NavigatorUtil.navigate.currentState != null) {
        BlocProvider.of<NotificationCountCubit>(
                NavigatorUtil.navigate.currentState!.context)
            .getNotificationCount();
      }
      FlutterAppBadger.updateBadgeCount(count++);
    }
    // count++;
    print("checkCount ${count}");
    print("checkCount ${count++}");
    print(
        "checkCount ${pref.getInt(SharedPreferencesUtil.keyNotificationCount)}");
    // pref.putInt(SharedPreferencesUtil.keyNotificationCount, count++);

    // if (NavigatorUtil.navigate.currentState != null) {
    //   BlocProvider.of<NotificationCountCubit>(
    //           NavigatorUtil.navigate.currentState!.context)
    //       .getNotificationCount();
    // }
    // FlutterAppBadger.updateBadgeCount(count++);
  }

  static Future<void> _showNotification(
    String title,
    String body,
    String payload,
  ) async {
    const AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails(
      'ipm001',
      'ipm_notification_chnnel',
      channelDescription: 'ipm_notification_chnnel',
      importance: Importance.max,
      priority: Priority.high,
    );

    const NotificationDetails notificationDetails =
        NotificationDetails(android: androidNotificationDetails);
    await flutterLocalNotificationsPlugin.show(
      0,
      title,
      body,
      notificationDetails,
      payload: payload,
    );
  }
}
