import 'dart:io';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:get/get.dart';
import 'package:siro_service/controller/local_notification.dart';
import '../../constant/box_name.dart';
import '../../main.dart';
import '../../print.dart';

@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  // If you're going to use other Firebase services in the background, such as Firestore,
  // make sure you call `initializeApp` before using other Firebase services.
  Log.print("Handling a background message: ${message.messageId}");

  if (message.data.isNotEmpty && message.notification != null) {
    // في وضع الخلفية، يفضل إرسال إشعار محلي أو تحديث البيانات الصامتة
  }
}

class FirebaseMessagesController extends GetxController {
  final fcmToken = FirebaseMessaging.instance;

  List<String> tokens = [];
  List dataTokens = [];
  late String driverID;
  late String driverToken;
  NotificationSettings? notificationSettings;

  Future<void> getNotificationSettings() async {
    // Get the current notification settings
    NotificationSettings? notificationSettings =
        await FirebaseMessaging.instance.getNotificationSettings();
    'Notification authorization status: ${notificationSettings.authorizationStatus}';

    // Call the update function if needed
    update();
  }

  Future<void> requestFirebaseMessagingPermission() async {
    FirebaseMessaging messaging = FirebaseMessaging.instance;

    // Check if the platform is Android
    if (Platform.isAndroid) {
      // Request permission for Android
      await messaging.requestPermission();
    } else if (Platform.isIOS) {
      // Request permission for iOS
      NotificationSettings settings = await messaging.requestPermission(
        alert: true,
        announcement: true,
        badge: true,
        carPlay: true,
        criticalAlert: true,
        provisional: false,
        sound: true,
      );
      messaging.setForegroundNotificationPresentationOptions(
          alert: true, badge: true, sound: true);
    }
  }

  // NotificationController notificationController =
  //     Get.isRegistered<NotificationController>()
  //         ? Get.find<NotificationController>()
  //         : Get.put(NotificationController());

  Future getToken() async {
    fcmToken.getToken().then((token) {
      // Log.print('fcmToken: ${token}');
      box.write(BoxName.tokenFCM, (token.toString()));
    });
    // 🔹 الاشتراك في topic
    await fcmToken.subscribeToTopic("service"); // أو "users" حسب نوع المستخدم
    Log.print("Subscribed to 'service' topic ✅");

    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      // If the app is in the background or terminated, show a system tray message
      if (message.data.isNotEmpty && message.notification != null) {
        fireBaseTitles(message);
      }
    });

    // استخدام الدالة العامة للهاندلر في الخلفية
    FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      if (message.data.isNotEmpty && message.notification != null) {
        fireBaseTitles(message);
      }
    });
  }

  Future<void> fireBaseTitles(RemoteMessage message) async {
    // [!! تعديل !!]
    // اقرأ "النوع" من حمولة البيانات، وليس من العنوان
    String category = message.data['category'] ?? '';

    // اقرأ العنوان (للعرض)
    String title = message.notification?.title ?? '';
    String body = message.notification?.body ?? '';

    if (category == 'new_service_request') {
      // <-- مثال: كان 'Order'.tr
      Log.print('message: ${message}');
      if (Platform.isAndroid) {
        NotificationController().showNotification(title, body, 'Order');
      }
    }
  }
}
