import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter/material.dart';
import 'api_service.dart';

class NotificationService {
  static final FirebaseMessaging _messaging = FirebaseMessaging.instance;
  static final FlutterLocalNotificationsPlugin _localNotifications =
      FlutterLocalNotificationsPlugin();

  static GlobalKey<NavigatorState>? navigatorKey;

  static Future<void> initialize() async {
    await _messaging.requestPermission(
      alert: true,
      badge: true,
      sound: true,
    );

    const androidSettings =
        AndroidInitializationSettings('@mipmap/ic_launcher');
    const initSettings = InitializationSettings(android: androidSettings);
    await _localNotifications.initialize(
      settings: initSettings,
      onDidReceiveNotificationResponse: _onNotificationTapped,
    );

    const channel = AndroidNotificationChannel(
      'reasonabledoubt_default',
      'Legal Notifications',
      description: 'Notifications for reminders, document updates and chat responses',
      importance: Importance.high,
    );
    await _localNotifications
        .resolvePlatformSpecificImplementation<
            AndroidFlutterLocalNotificationsPlugin>()
        ?.createNotificationChannel(channel);

    FirebaseMessaging.onMessage.listen(_handleForegroundMessage);
    FirebaseMessaging.onMessageOpenedApp.listen(_handleNotificationNavigation);

    final initialMessage = await _messaging.getInitialMessage();
    if (initialMessage != null) {
      Future.delayed(const Duration(milliseconds: 500), () {
        _handleNotificationNavigation(initialMessage);
      });
    }

    await _registerToken();

    _messaging.onTokenRefresh.listen((token) async {
      await _sendTokenToServer(token);
    });
  }

  static ApiService? _api;
  
  static void setApi(ApiService api) {
    _api = api;
  }

  static Future<void> _registerToken() async {
    try {
      final token = await _messaging.getToken();
      if (token != null) {
        await _sendTokenToServer(token);
      }
    } catch (_) {}
  }

  static Future<void> _sendTokenToServer(String token) async {
    if (_api == null) return;
    try {
      await _api!.updateFcmToken(token);
    } catch (_) {}
  }

  static void _handleForegroundMessage(RemoteMessage message) {
    final notification = message.notification;
    if (notification == null) return;

    _localNotifications.show(
      id: notification.hashCode,
      title: notification.title,
      body: notification.body,
      notificationDetails: const NotificationDetails(
        android: AndroidNotificationDetails(
          'reasonabledoubt_default',
          'Legal Notifications',
          importance: Importance.high,
          priority: Priority.high,
        ),
      ),
      payload: message.data['type'] ?? '',
    );
  }

  static void _onNotificationTapped(NotificationResponse response) {
    final type = response.payload;
    if (navigatorKey?.currentState == null) return;
    switch (type) {
      case 'reminder':
        navigatorKey!.currentState!.pushNamed('/reminders');
      case 'document':
        navigatorKey!.currentState!.pushNamed('/documents');
      case 'chat':
        navigatorKey!.currentState!.pushNamed('/home');
      default:
        navigatorKey!.currentState!.pushNamed('/home');
    }
  }

  static void _handleNotificationNavigation(RemoteMessage message) {
    final type = message.data['type'];
    if (navigatorKey?.currentState == null) return;
    switch (type) {
      case 'reminder':
        navigatorKey!.currentState!.pushNamed('/reminders');
      case 'document':
        navigatorKey!.currentState!.pushNamed('/documents');
      case 'chat':
        navigatorKey!.currentState!.pushNamed('/home');
      default:
        navigatorKey!.currentState!.pushNamed('/home');
    }
  }
}
