import 'dart:io';
import 'dart:convert';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:mypoint_flutter_app/core/firebase/push_notification.dart';
import '../platform/firebase/firebase_options.dart';
import 'notification_parse_payload.dart';

@pragma('vm:entry-point') // bắt buộc cho background isolate
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  debugPrint('_firebaseMessagingBackgroundHandler ${message.toMap()}');

  // Android: data-only message sẽ không tự hiển thị. Tự show local notification
  if (!kIsWeb && Platform.isAndroid) {
    final data = message.data;
    final title = message.notification?.title ?? data['title']?.toString();
    final body = message.notification?.body ?? (data['body']?.toString() ?? data['content']?.toString());
    if ((title ?? body) != null) {
      await _ensureBgLocalNotifications();
      await _flnp.show(
        message.hashCode,
        title,
        body,
        const NotificationDetails(
          android: AndroidNotificationDetails(
            'default_channel',
            'General',
            importance: Importance.high,
            priority: Priority.high,
          ),
        ),
        payload: data.isNotEmpty ? jsonEncode(data) : null,
      );
    }
  }
}

final _flnp = FlutterLocalNotificationsPlugin();
bool _bgLocalInit = false;

Future<void> _ensureBgLocalNotifications() async {
  if (_bgLocalInit) return;
  const androidInit = AndroidInitializationSettings('@mipmap/ic_launcher');
  const iosInit = DarwinInitializationSettings();
  const init = InitializationSettings(android: androidInit, iOS: iosInit);
  await _flnp.initialize(init);

  const channel = AndroidNotificationChannel(
    'default_channel',
    'General',
    description: 'Default notifications',
    importance: Importance.high,
  );
  await _flnp
      .resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()
      ?.createNotificationChannel(channel);
  _bgLocalInit = true;
}

Future<void> _initLocalNotifications() async {
  const androidInit = AndroidInitializationSettings('@mipmap/ic_launcher');
  const iosInit = DarwinInitializationSettings();
  const init = InitializationSettings(android: androidInit, iOS: iosInit);
  // Thêm callback xử lý khi click notification
  await _flnp.initialize(
    init,
    onDidReceiveNotificationResponse: (response) {
      debugPrint('Response: $response, payload: ${response.payload}');
      final info = parseNotificationPayload(response.payload);
      NotificationRouter.handleDirectionNotification(PushNotification(info: info));
    },
  );
  const channel = AndroidNotificationChannel(
    'default_channel',
    'General',
    description: 'Default notifications',
    importance: Importance.high,
  );
  await _flnp
      .resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()
      ?.createNotificationChannel(channel);
}

/// Kiểm tra nếu app được mở do click vào local notification (từ killed state)
Future<void> handleLocalNotificationLaunchIfAny() async {
  try {
    final details = await _flnp.getNotificationAppLaunchDetails();
    if (details == null) return;
    if (details.didNotificationLaunchApp) {
      final payload = details.notificationResponse?.payload;
      if (payload != null && payload.isNotEmpty) {
        final info = parseNotificationPayload(payload);
        Future.delayed(const Duration(seconds: 1), () {
          NotificationRouter.handleDirectionNotification(PushNotification(info: info));
        });
      }
    }
  } catch (_) {}
}

Future<void> initFirebaseAndFcm() async {
  FirebaseMessaging? messaging;
  try {
    await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
    FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
    messaging = FirebaseMessaging.instance;

    // Quyền iOS / Android 13+ / Web: chỉ tắt trên Web, mobile giữ nguyên
    if (kIsWeb) {
      // Tắt auto init để tránh plugin tự động thao tác permission trên web
      try {
        await FirebaseMessaging.instance.setAutoInitEnabled(false);
        debugPrint('Web: FCM auto-init disabled');
      } catch (_) {}
      debugPrint('Web: skip requesting notification permission at startup');
    } else if (Platform.isIOS) {
      await messaging.requestPermission(alert: true, badge: true, sound: true);
    } else {
      await messaging.requestPermission(); // Android 13+ POST_NOTIFICATIONS
    }

    await _initLocalNotifications();
  } catch (e) {
    debugPrint('Firebase initialization error: $e');
    // Continue without Firebase on web if there's an error
    if (kIsWeb) {
      return;
    }
    rethrow;
  }

  // Foreground: Android không tự hiển thị -> ta show local notification
  FirebaseMessaging.onMessage.listen((message) {
    debugPrint('=== FOREGROUND MESSAGE RECEIVED ===');
    debugPrint('Message: ${message.messageId}');
    debugPrint('Data: ${message.data}');
    debugPrint('Notification: ${message.notification?.title} - ${message.notification?.body}');
    // Only show local notifications on mobile platforms, not web
    if (!kIsWeb) {
      final n = message.notification;
      final title = n?.title ?? (message.data['title']?.toString());
      final body = n?.body ?? (message.data['body']?.toString());
      if ((title ?? body) != null) {
        _flnp.show(
          message.hashCode,
          title,
          body,
          const NotificationDetails(
            android: AndroidNotificationDetails(
              'default_channel',
              'General',
              importance: Importance.high,
              priority: Priority.high,
            ),
          ),
          payload: message.data.isNotEmpty ? jsonEncode(message.data) : null,
        );
      }
    }
  });
  // User click notification mở app (khi app đang chạy ở background)
  FirebaseMessaging.onMessageOpenedApp.listen((message) {
    NotificationRouter.handleRemoteMessage(message);
  });
  // Initial message sẽ được xử lý sau khi runApp trong main.dart
  // Lấy token để test gửi (bật cho mobile, tắt cho web)
  if (!kIsWeb) {
    try {
      final token = await messaging.getToken();
      debugPrint('FCM token: $token');
    } catch (e) {
      debugPrint('Error getting FCM token: $e');
    }
  }
}

/// Call this on WEB from a user gesture (e.g., button tap) to request notification permission.
Future<AuthorizationStatus?> requestWebNotificationPermission() async {
  // ĐÃ TẮT CHO WEB: Không request permission trên web
  if (kIsWeb) {
    debugPrint('Web notifications disabled: skip requesting permission');
    return AuthorizationStatus.denied;
  }
  return null;
}

/// Get FCM token if available. On Web, ensure permission is granted first.
Future<String?> getFcmTokenIfAvailable() async {
  try {
    final messaging = FirebaseMessaging.instance;
    if (kIsWeb) {
      final settings = await messaging.getNotificationSettings();
      if (settings.authorizationStatus != AuthorizationStatus.authorized) {
        debugPrint('Web notifications not authorized. Cannot retrieve FCM token.');
        return null;
      }
    }
    final token = await messaging.getToken();
    debugPrint('FCM token (if available): $token');
    return token;
  } catch (e) {
    debugPrint('Error retrieving FCM token: $e');
    return null;
  }
}
