import 'dart:convert';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:firebase_messaging/firebase_messaging.dart';

import '../utils/local_storage.dart';

class FirebaseNotificationService {
  static FirebaseMessaging messaging = FirebaseMessaging.instance;

  static void initService() async {
    var token = await messaging.getToken() ?? '';
    LocalStorage.save(LocalStorageKey.device_key, token);
    print('pushKey: $token');

    //config Android channel
    const channel = AndroidNotificationChannel(
      'high_importance_channel',
      'High Importance Notifications',
      importance: Importance.max,
    );
    final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

    await flutterLocalNotificationsPlugin
        .resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()
        ?.createNotificationChannel(channel);

    //handle message on background android
    FirebaseMessaging.onBackgroundMessage(
      _firebaseMessagingBackgroundHandler,
    );

    //Message foreground
    FirebaseMessaging.onMessage.listen(
      (RemoteMessage message) {
        print('Got a message whilst in the foreground!');
        print('Message data: $message');
        // increase count unread notification

        var remoteNotification = message.notification;
        var androidNotification = message.notification?.android;

        //
        var androidDetails = const AndroidNotificationDetails(
          'default_notification_channel_id',
          'Notification',
          importance: Importance.max,
          priority: Priority.high,
          icon: '@mipmap/ic_stat_ic_notification',
        );
        const iOSDetails = IOSNotificationDetails();

        var platformChannelSpecifics = NotificationDetails(
          android: androidDetails,
          iOS: iOSDetails,
        );

        //Show notification foreground android
        if (remoteNotification != null && androidNotification != null) {
          flutterLocalNotificationsPlugin.show(
            0,
            remoteNotification.title,
            remoteNotification.body,
            platformChannelSpecifics,
            // NotificationDetails(
            //   android: AndroidNotificationDetails(
            //     channel.id,
            //     channel.name,
            //     icon: '@mipmap/ic_stat_ic_notification',
            //   ),
            // ),
          );
        }
        flutterLocalNotificationsPlugin.show(
          0,
          remoteNotification?.title ?? '',
          remoteNotification?.body ?? '',
          platformChannelSpecifics,
          // NotificationDetails(
          //   android: AndroidNotificationDetails(
          //     channel.id,
          //     channel.name,
          //     icon: '@mipmap/ic_stat_ic_notification',
          //   ),
          // ),
        );
      },
    );

    //Interaction Message from background
    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      print('message from background: ${message}');
      _handleMessage(message);
    });

    //Interaction Message from terminal
    var initialMessage = await FirebaseMessaging.instance.getInitialMessage();
    print('initialMessage: $initialMessage');
    if (initialMessage != null) {
      _handleMessage(initialMessage);
    }
  }

  static Future onDidReceiveLocalNotification(int? id, String? title, String? body, String? payload) async {
    // display a dialog with the notification details, tap ok to go to another page
  }

  static Future selectNotification(String? payload) async {
    try {
      var data = json.decode(payload ?? '');
      handleNavigateScreen(data);
    } catch (e) {
      print(e);
    }
  }

  static void _handleMessage(RemoteMessage message) {
    try {
      var data = message.data;
      handleNavigateScreen(data);
    } catch (e) {
      print(e);
    }
  }

  static void handleNavigateScreen(dynamic data) {}
}

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  print('Handling a background message: ${message}');
}
