import 'dart:developer' as dev;
import 'dart:math' as math;
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

class NotificationServices {
  FirebaseMessaging messaging = FirebaseMessaging.instance;
  final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();

  void firebaseInit(BuildContext context) async {
    FirebaseMessaging.onMessage.listen((message) {
      initNotifications(context, message);
      showNotification(message);
      dev.log(
          "Title: ${message.notification!.title}, Body: ${message.notification!.body} from ${message.sentTime}");
    });
  }

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

  void isTokenRefresh() async {
    messaging.onTokenRefresh.listen((newToken) {
      dev.log("Refresh Firebase Messaging Token: $newToken");
    });
  }

  void initNotifications(BuildContext context, RemoteMessage message) async {
    var androidInitializationSettings =
        const AndroidInitializationSettings('app_icon');
    var iosInitializationSettings = const DarwinInitializationSettings();
    var initializationSettings = InitializationSettings(
        android: androidInitializationSettings, iOS: iosInitializationSettings);
    await _flutterLocalNotificationsPlugin.initialize(initializationSettings,
        onDidReceiveNotificationResponse: (payload) {
      handleMessage(context, message);
    });
  }

  Future<void> showNotification(RemoteMessage message) async {
    AndroidNotificationChannel androidNotificationChannel =
        AndroidNotificationChannel(
            math.Random.secure().nextInt(1000000).toString(),
            'high Important Notification',
            importance: Importance.max);
    AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails(
      androidNotificationChannel.id.toString(),
      androidNotificationChannel.name.toString(),
      sound: RawResourceAndroidNotificationSound(message.data['sound']),
      channelDescription: "Channel description",
      importance: androidNotificationChannel.importance,
      priority: Priority.high,
      ticker: 'ticker',
    );

    const DarwinNotificationDetails darwinNotificationDetails =
        DarwinNotificationDetails(
      presentAlert: true,
      presentBadge: true,
      presentBanner: true,
      presentSound: true,
    );
    NotificationDetails notificationDetails = NotificationDetails(
        android: androidNotificationDetails, iOS: darwinNotificationDetails);
    Future.delayed(Duration.zero, () {
      _flutterLocalNotificationsPlugin.show(0, message.notification!.title!,
          message.notification!.body, notificationDetails);
    });
  }

  void handleMessage(BuildContext context, RemoteMessage message) async {
    if (message.data['type'] == "msj") {
      // Navigator.push(context,
      //     MaterialPageRoute(builder: (context) => const MessageScreen()));
    } else if (message.data['type'] == "warn") {
      // Navigator.push(
      //     context, MaterialPageRoute(builder: (context) => const MapScreen()));
    } else {
      dev.log("Not found data");
    }
  }

  Future<void> setupInteractMessage(BuildContext context) async {
    // When app terminate
    RemoteMessage? initialMessage =
        await FirebaseMessaging.instance.getInitialMessage();
    if (initialMessage != null) {
      // showNotification(initialMessage);
      // ignore: use_build_context_synchronously
      handleMessage(context, initialMessage);
    }

    // When app is inBackGround
    FirebaseMessaging.onMessageOpenedApp.listen((message) {
      handleMessage(context, message);
    });
  }
}
