// firebase_config.dart

import 'dart:typed_data';
import 'package:absenkuv3/Setting/RouteNavFCM.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:url_launcher/url_launcher.dart';

FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();
String? routenya;
Future<void> initializeFirebase() async {
  await Firebase.initializeApp();
  await Permission.notification.request();
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);


  const AndroidInitializationSettings initializationSettingsAndroid =
      AndroidInitializationSettings('@mipmap/ic_launcher');
  // final DarwinInitializationSettings initializationSettingsIOS =
  //     DarwinInitializationSettings(
  //         onDidReceiveLocalNotification: onDidReceiveLocalNotification);
  final DarwinInitializationSettings initializationSettingsIOS =
    DarwinInitializationSettings();

  final DarwinInitializationSettings initializationSettingsMacOS =
      DarwinInitializationSettings();
  final InitializationSettings initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid,
      iOS: initializationSettingsIOS,
      macOS: initializationSettingsMacOS);

  await flutterLocalNotificationsPlugin.initialize(
    initializationSettings,
    onDidReceiveNotificationResponse: (NotificationResponse notificationResponse) {
      switch (notificationResponse.notificationResponseType) {
        case NotificationResponseType.selectedNotification:
          selectNotification(notificationResponse.payload);
          break;
        case NotificationResponseType.selectedNotificationAction:
          break;
        default:
          break;
      }
    },
    onDidReceiveBackgroundNotificationResponse: notificationTapBackground,
  );

  FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
    routenya = message.data['route_nav'];
    _showNotificationWithoutSound(message);
    if (message.notification != null) {
      print('Message also contained a notification: ${message.notification}');
    }
  });

  FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
    RouteForegroundBackground(message.data['route_nav'], message.data['id_ref']);
    print('A new onMessageOpenedApp event was published!');
  });
}

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

void notificationTapBackground(NotificationResponse notificationResponse) {
  print('notification(${notificationResponse.id}) action tapped: '
      '${notificationResponse.actionId} with payload: ${notificationResponse.payload}');
  if (notificationResponse.input?.isNotEmpty ?? false) {
    print('notification action tapped with input: ${notificationResponse.input}');
  }
}

void selectNotification(String? idRef) async {
  if (idRef != null) RouteForegroundBackground(routenya, idRef);
}

void onDidReceiveLocalNotification(
    int id, String? title, String? body, String? payload) async {}

Future<void> _showNotificationWithoutSound(RemoteMessage message) async {
  String? title = message.notification?.title;
  String? body = message.notification?.body;
  String? idRef = message.data['id_ref'];
  List<int> vibrationPattern = [0, 1000, 500, 1000];
  Int64List int64VibrationPattern = Int64List.fromList(vibrationPattern);

  AndroidNotificationDetails androidPlatformChannelSpecifics;
  if (message.data['sound'] == null || message.data['sound'] == "") {
    androidPlatformChannelSpecifics = AndroidNotificationDetails(
      'channel_id_2',
      'general',
      channelDescription: 'your channel description',
      playSound: true,
      importance: Importance.max,
      enableVibration: true,
      vibrationPattern: int64VibrationPattern,
      priority: Priority.high,
    );
  } else if (message.data['sound'] == "emergency") {
    androidPlatformChannelSpecifics = AndroidNotificationDetails(
      'channel_id_3',
      'emergency',
      channelDescription: 'your channel description',
      playSound: true,
      sound: RawResourceAndroidNotificationSound("emergency"),
      importance: Importance.max,
      enableVibration: true,
      vibrationPattern: int64VibrationPattern,
      priority: Priority.high,
    );
  } else {
    androidPlatformChannelSpecifics = AndroidNotificationDetails(
      'channel_id_1',
      'absensi',
      channelDescription: 'absensi',
      playSound: true,
      sound: RawResourceAndroidNotificationSound('access'),
      importance: Importance.max,
      enableVibration: true,
      vibrationPattern: int64VibrationPattern,
      priority: Priority.high,
    );
  }

  DarwinNotificationDetails iOSPlatformChannelSpecifics;
  if (message.data['sound'] == null || message.data['sound'] == "") {
    iOSPlatformChannelSpecifics = DarwinNotificationDetails(presentSound: false);
  } else if (message.data['sound'] == "emergency") {
    iOSPlatformChannelSpecifics = DarwinNotificationDetails(presentSound: true, sound: 'emergency.caf');
  } else {
    iOSPlatformChannelSpecifics = DarwinNotificationDetails(presentSound: true, sound: 'absenku.caf');
  }

  var platformChannelSpecifics = NotificationDetails(
      android: androidPlatformChannelSpecifics,
      iOS: iOSPlatformChannelSpecifics);

  await FirebaseMessaging.instance
      .setForegroundNotificationPresentationOptions(alert: true, badge: true, sound: true);
  await flutterLocalNotificationsPlugin.show(
    DateTime.now().millisecondsSinceEpoch.remainder(1 << 31),
    title,
    body,
    platformChannelSpecifics,
    payload: idRef,
  );
}

Future<void> launcherUrl(String link) async {
  if (await canLaunch(link)) {
    await launch(link);
  } else {
    throw 'Could not launch $link';
  }
}
