import 'package:didvan/models/notification_data.dart';
import 'package:didvan/models/notification_message.dart';
import 'package:didvan/services/app_home_widget/home_widget_repository.dart';
import 'package:didvan/services/app_initalizer.dart';
import 'package:didvan/services/notification/notification_service.dart';
import 'package:didvan/services/storage/storage.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';

class FirebaseApi {
  final _firebaseMessaging = FirebaseMessaging.instance;
  static String? fcmToken;

  Future<void> initNotification() async {
    try {
      fcmToken = await _firebaseMessaging.getToken();
      if (kDebugMode) {
        print("fCMToken: $fcmToken");
      }
    } catch (e) {
      e.printError();
    }

    _firebaseMessaging.requestPermission(
      alert: true,
      announcement: true,
      badge: true,
      carPlay: false,
      criticalAlert: true,
      provisional: true,
      sound: true,
    );

    final initMsg = await FirebaseMessaging.instance.getInitialMessage();

    if (initMsg != null) {
      if (kDebugMode) {
        print("=== APP OPENED FROM NOTIFICATION (TERMINATED) ===");
        print("Message ID: ${initMsg.messageId}");
        print("Raw Data: ${initMsg.data}");
        if (initMsg.notification != null) {
          print("Title: ${initMsg.notification!.title}");
          print("Body: ${initMsg.notification!.body}");
        }
        print("================================================");
      }
      
      try {
        NotificationMessage data = NotificationMessage.fromJson(initMsg.data);
        HomeWidgetRepository.data = data;
        if (kDebugMode) {
          print("Parsed NotificationMessage: ${data.toJson()}");
        }
        await HomeWidgetRepository.decideWhereToGoNotif();
        await StorageService.delete(
            key: 'notification${AppInitializer.createNotificationId(data)}');
      } catch (e) {
        if (kDebugMode) {
          print("Error handling initial message: $e");
        }
        e.printError();
      }
    }

    FirebaseMessaging.onMessageOpenedApp.listen((initMsg) async {
      if (kDebugMode) {
        print("=== APP OPENED FROM NOTIFICATION (BACKGROUND) ===");
        print("Message ID: ${initMsg.messageId}");
        print("Raw Data: ${initMsg.data}");
        if (initMsg.notification != null) {
          print("Title: ${initMsg.notification!.title}");
          print("Body: ${initMsg.notification!.body}");
        }
        print("================================================");
      }
      
      try {
        NotificationMessage data = NotificationMessage.fromJson(initMsg.data);
        HomeWidgetRepository.data = data;
        if (kDebugMode) {
          print("Parsed NotificationMessage: ${data.toJson()}");
        }
        await HomeWidgetRepository.decideWhereToGoNotif();
        await StorageService.delete(
            key: 'notification${AppInitializer.createNotificationId(data)}');
      } catch (e) {
        if (kDebugMode) {
          print("Error handling background message: $e");
        }
        e.printError();
      }
    });

    FirebaseMessaging.onMessage.listen((event) => handleMessage(event));
  }

  void handleMessage(RemoteMessage? message) async {
    if (message == null) return;
    
    if (kDebugMode) {
      print("=== NOTIFICATION RECEIVED (FOREGROUND) ===");
      print("Message ID: ${message.messageId}");
      print("From: ${message.from}");
      print("Sent Time: ${message.sentTime}");
      print("TTL: ${message.ttl}");
      print("Message Type: ${message.messageType}");
      print("Category: ${message.category}");
      
      if (message.notification != null) {
        print("--- NOTIFICATION PAYLOAD ---");
        print("Title: ${message.notification!.title}");
        print("Body: ${message.notification!.body}");
        print("Android Image: ${message.notification!.android?.imageUrl}");
        print("Apple Image: ${message.notification!.apple?.imageUrl}");
      }
      
      print("--- DATA PAYLOAD ---");
      print("Raw Data: ${message.data}");
      try {
        NotificationData notifData = NotificationData.fromJson(message.data);
        print("Parsed Data: ${notifData.toJson()}");
      } catch (e) {
        print("Error parsing NotificationData: $e");
      }
      
      print("==========================================");
    }
    
    try {
      await NotificationService.showFirebaseNotification(message);
    } catch (e) {
      e.printError();
    }
  }
}
