import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

import '../network/api_client.dart';

class FcmService {
  final ApiClient _apiClient;
  final FirebaseMessaging _messaging = FirebaseMessaging.instance;
  final FlutterLocalNotificationsPlugin _localNotifications = FlutterLocalNotificationsPlugin();

  FcmService(this._apiClient);

  Future<void> init() async {
    if (kIsWeb) return;
    try {
      await _localNotifications.initialize(
        const InitializationSettings(
          android: AndroidInitializationSettings('@mipmap/ic_launcher'),
        ),
      );
      await _messaging.requestPermission(alert: true, badge: true, sound: true);
      final token = await _messaging.getToken();
      if (token != null) await syncToken(token);
      FirebaseMessaging.instance.onTokenRefresh.listen(syncToken);
      FirebaseMessaging.onMessage.listen((message) {
        debugPrint('FCM foreground: ${message.data}');
        _showLocalNotification(message);
      });
    } catch (e) {
      debugPrint('FCM init skipped: $e');
    }
  }

  Future<void> syncToken(String token) async {
    try {
      await _apiClient.dio.put('/auth/fcm-token', data: {'fcmToken': token});
    } catch (e) {
      debugPrint('FCM token sync skipped: $e');
    }
  }

  Future<void> _showLocalNotification(RemoteMessage message) async {
    final notification = message.notification;
    final title = notification?.title ?? message.data['title']?.toString() ?? 'WalkGuide';
    final body = notification?.body ?? message.data['body']?.toString() ?? 'Ada update baru';
    await _localNotifications.show(
      DateTime.now().millisecondsSinceEpoch ~/ 1000,
      title,
      body,
      const NotificationDetails(
        android: AndroidNotificationDetails(
          'walkguide_alerts',
          'WalkGuide Alerts',
          channelDescription: 'SOS, pairing, call, and guardian notifications',
          importance: Importance.max,
          priority: Priority.high,
        ),
      ),
      payload: message.data['type']?.toString(),
    );
  }
}
