// ignore_for_file: avoid_print

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:go_router/go_router.dart';
import 'package:hoshan/core/routes/route_generator.dart';
import 'package:hoshan/data/model/ai/bots_model.dart';
import 'package:hoshan/data/model/chat_args.dart';
import 'package:hoshan/main.dart';
import 'package:package_info_plus/package_info_plus.dart';

class FirebasApi {
  static final _firebaseMessaging = FirebaseMessaging.instance;
  static Bots? bot;
  static String? fcmToken;

  static Future<void> initialNotifications() async {
    await refreshToken();

    try {
      await _firebaseMessaging.subscribeToTopic('all_users').timeout(
        const Duration(seconds: 10),
        onTimeout: () {
          print('⏰ Subscribe to topic timed out - continuing anyway');
        },
      );
      print('✅ Subscribed to topic: all_users');
    } catch (e) {
      print('❌ Failed to subscribe to topic (app will continue): $e');
    }

    initPushNotification();
  }

  static Future refreshToken() async {
    try {
      print('🔄 Start getting FCM Token...');
      await _firebaseMessaging.requestPermission();

      fcmToken = await _firebaseMessaging.getToken().timeout(
        const Duration(seconds: 10),
        onTimeout: () {
          print('⏰ FCM Token request timed out - continuing without token');
          return null;
        },
      );

      final packageInfo = await PackageInfo.fromPlatform();
      final packageName = packageInfo.packageName;

      print('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
      print('📦 Package Name: $packageName');
      print('🔥 Firebase Initialized Successfully');
      print('📱 FCM Token: $fcmToken');
      print('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    } catch (e) {
      print('❌ ERROR Getting Token (app will continue): $e');
    }
  }

  static Future deleteToken() async {
    try {
      await _firebaseMessaging.deleteToken();
    } catch (e) {
      if (kDebugMode) {
        print('Error while firebaseMessaging deleteToken: $e');
      }
    }
  }

  static void handleMessage(RemoteMessage? message) async {
    if (message == null) return;
    bot = Bots.fromNotification(message.data);
    if (navigatorKey.currentState != null) {
      if (bot!.tool ?? false) {
        navigatorKey.currentContext?.go(Routes.assistant, extra: bot!.id);
      } else {
        navigatorKey.currentContext
            ?.go(Routes.chat, extra: ChatArgs(bot: bot!));
      }
      bot = null;
    }
  }

  static Future initPushNotification() async {
    FirebaseMessaging.instance.getInitialMessage().then(handleMessage);
    FirebaseMessaging.onMessageOpenedApp.listen(handleMessage);
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      if (message.notification != null) {
        if (navigatorKey.currentContext != null) {
          ScaffoldMessenger.of(navigatorKey.currentContext!).showSnackBar(
            SnackBar(
              content: Text(
                message.notification!.title != null
                    ? '${message.notification!.title}\n${message.notification!.body}'
                    : '${message.notification!.body}',
                textDirection: TextDirection.rtl,
              ),
              behavior: SnackBarBehavior.floating,
              showCloseIcon: true,
            ),
          );
        }
      }
    });
  }
}
