import 'dart:convert';

import 'package:farm_tpf/presentation/screens/task/task_detail_page.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:get/get.dart';
import '../presentation/screens/plot_detail/sc_plot_detail.dart';
import '../utils/pref.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

class FirebaseNotificationService {
  static FirebaseMessaging messaging = FirebaseMessaging.instance;
  static final _pref = LocalPref();

  static void initService() async {
    var token = await messaging.getToken() ?? '';
    await _pref.saveString(PrefKey.push_key, token);
    print('pushKey: $token');

    //config Android channel
    const channel = AndroidNotificationChannel(
      'high_importance_channel',
      'High Importance Notifications',
      importance: Importance.max,
    );
    final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

    await flutterLocalNotificationsPlugin
        .resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()
        ?.createNotificationChannel(channel);

    await flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>()?.requestPermissions(
          alert: true,
          badge: true,
          sound: true,
        );

    //handle message on background android
    FirebaseMessaging.onBackgroundMessage(
      _firebaseMessagingBackgroundHandler,
    );

    //Message foreground
    FirebaseMessaging.onMessage.listen(
      (RemoteMessage message) {
        print('Got a message whilst in the foreground!');
        print('Message data: ${messaging.toString()}');
        // increase count unread notification
        // countNotificationUnRead.value = countNotificationUnRead.value + 1;

        var remoteNotification = message.notification;
        var androidNotification = message.notification?.android;

        var flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
        const initializationSettingsAndroid = AndroidInitializationSettings(
          'app_icon',
        );
        const initializationSettingsIOS = DarwinInitializationSettings(
          requestSoundPermission: false,
          requestBadgePermission: false,
          requestAlertPermission: false,
          onDidReceiveLocalNotification: onDidReceiveLocalNotification,
        );

        const initializationSettings = InitializationSettings(
          android: initializationSettingsAndroid,
          iOS: initializationSettingsIOS,
        );
        flutterLocalNotificationsPlugin.initialize(
          initializationSettings,
          // onDidReceiveNotificationResponse: selectNotification,
          onDidReceiveNotificationResponse: (NotificationResponse notificationResponse) async {
            await selectNotification(notificationResponse.payload);
          },
        );

        var androidDetails = const AndroidNotificationDetails(
          'default_notification_channel_id',
          'Notification',
          importance: Importance.max,
          priority: Priority.high,
          icon: '@mipmap/ic_stat_ic_notification',
        );

        var platformChannelSpecifics = NotificationDetails(
          android: androidDetails,
        );

        try {
          var dataPayload = json.encode(message.data);
          // var entityType = message.data['entity_type'];
          // var entityData = message.data['entity_data'];
          // var systemMessage = message.data['system_message'];
          print('normal message');
          flutterLocalNotificationsPlugin.show(
            0,
            message.notification?.title,
            message.notification?.body,
            platformChannelSpecifics,
            payload: dataPayload,
          );
        } catch (e) {
          print(e);
        }
      },
    );

    //Interaction Message from background
    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      print('message from background: ${message}');
      _handleMessage(message);
    });

    //Interaction Message from terminal
    var initialMessage = await FirebaseMessaging.instance.getInitialMessage();
    print('initialMessage: $initialMessage');
    if (initialMessage != null) {
      _handleMessage(initialMessage);
    }
  }

  static Future onDidReceiveLocalNotification(int? id, String? title, String? body, String? payload) async {
    // display a dialog with the notification details, tap ok to go to another page
    print('handle touch on foreground');
  }

  static Future selectNotification(String? payload) async {
    try {
      var data = json.decode(payload ?? '');
      handleNavigateScreen(data);
    } catch (e) {
      print(e);
    }
  }

  static void _handleMessage(RemoteMessage message) {
    try {
      var data = message.data;
      handleNavigateScreen(data);
    } catch (e) {
      print(e);
    }
  }

  static void handleNavigateScreen(dynamic data) {
    try {
      if (data['contents'] == 'TODO_LIST_CREATE' || data['contents'] == 'TODO_LIST_UPDATE') {
        Get.to(() => TaskDetailPage(taskId: int.tryParse(data['externalId']) ?? -1));
      } else if (data['contents'] == 'ENV_UPDATE') {
        Get.to(
          () => PlotDetailScreen(
            cropType: int.tryParse(data['tbCropType']) ?? -1,
            cropId: int.tryParse(data['tbCropId']) ?? -1,
            initialIndex: 0,
          ),
        );
      } else if (data['contents'] == 'PIC_UPDATE') {
        Get.to(
          () => PlotDetailScreen(
            cropType: int.tryParse(data['tbCropType']) ?? -1,
            cropId: int.tryParse(data['tbCropId']) ?? -1,
            initialIndex: 1,
          ),
        );
      } else {
        print(data['contents']);
      }
      print(data);
    } catch (e) {
      print(e);
    }
  }

  static Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
    print('Handling a background message: ${message}');
    _handleMessage(message);
  }
}
