import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:peasmartcare/models/firebase_notification_model.dart';

class NotificationFirebase {
  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
  final FirebaseMessaging firebaseMessaging;
  final onBackgroundMessageHandler;
  // final BuildContext context;

  FirebaseNotificationModel firebaseNotiData;
  String message = "No message.";
  String channelId = "1000";
  String channelName = "pea_notification";
  String channelDescription = "FLUTTER_NOTIFICATION_CHANNEL_DETAIL";

  NotificationFirebase({
    // @required this.context,
    @required this.onBackgroundMessageHandler,
    @required this.firebaseMessaging,
  });

  FirebaseMessaging initNotificationFirebase() {
    firebaseMessaging.subscribeToTopic(channelName);

    var initializationSettingsAndroid = AndroidInitializationSettings("launcher_icon");

    var initializationSettingsIOS = IOSInitializationSettings(
      onDidReceiveLocalNotification: onDidReceiveLocalNotification,
    );
    var initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid,
      iOS: initializationSettingsIOS,
    );

    flutterLocalNotificationsPlugin.initialize(initializationSettings, onSelectNotification: onSelectNotification);
    // flutterLocalNotificationsPlugin.initialize(initializationSettings);

    firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async {
        print("==> onMessage: $message");

        firebaseNotiData = _getNotificationMessage(message);

        // String title = notiData['title'];
        // String body = notiData['body'];
        // String payload = ""; //notiData['payload'];

        // sendNotification(title: title, body: body, payload: payload);
        print("notiType");
        print(firebaseNotiData.notiType);
        if (firebaseNotiData.notiType.toUpperCase() != "CHAT") {
          sendNotification(firebaseNotiData);
        } else {
          // context.read<ChatListBloc>().add(
          //       ChatListGetList(
          //         isNewMessage: firebaseNotiData.isNewMessageChat,
          //         isGroupChat: firebaseNotiData.isGroupChat,
          //         typeChat: firebaseNotiData.typeChat,
          //         chatMasterId: firebaseNotiData.chatMasterId,
          //         typeAccount: firebaseNotiData.chatTypeAccount,
          //       ),
          //     );
        }

        _countNotification(firebaseNotiData.notiType);
      },
      onBackgroundMessage: onBackgroundMessageHandler,
      onLaunch: (Map<String, dynamic> message) async {
        print("==> onLaunch: $message");
        firebaseNotiData = _getNotificationMessage(message);

        _countNotification(firebaseNotiData.notiType);
        onSelectNotification(firebaseNotiData.payload);
      },
      onResume: (Map<String, dynamic> message) async {
        print("==> onResume: $message");
        firebaseNotiData = _getNotificationMessage(message);

        // String title = notiData['title'];
        // String body = notiData['body'];
        // String payload = notiData['payload'];

        // sendNotification(title: title, body: body, payload: payload);
        // sendNotification(notiData);

        _countNotification(firebaseNotiData.notiType);
        onSelectNotification(firebaseNotiData.payload);
      },
    );
    firebaseMessaging.requestNotificationPermissions(const IosNotificationSettings(
      sound: true,
      badge: true,
      alert: true,
      provisional: true,
    ));
    firebaseMessaging.onIosSettingsRegistered.listen((IosNotificationSettings settings) {
      print("Settings registered: $settings");
    });
    firebaseMessaging.getToken().then((String token) async {
      assert(token != null);
      print("==> ##########################");
      print("==> " + token);
      print("==> ##########################");

      // setState(() {
      //   _homeScreenText = "Push Messaging token: $token";
      // });
      // print(_homeScreenText);
    });
  }

  sendNotification(FirebaseNotificationModel item) async {
    print("==> sendNotification");
    var androidPlatformChannelSpecifics = AndroidNotificationDetails(
      channelId,
      channelName,
      channelDescription,
      importance: Importance.max,
      priority: Priority.high,
    );
    var iOSPlatformChannelSpecifics = IOSNotificationDetails();
    var platformChannelSpecifics = NotificationDetails(android: androidPlatformChannelSpecifics, iOS: iOSPlatformChannelSpecifics);

    // item.toJson();

    await flutterLocalNotificationsPlugin.show(
      0,
      item.title,
      item.body,
      platformChannelSpecifics,
      payload: item.payload,
    );
  }

  _getNotificationMessage(Map<String, dynamic> message) {
    FirebaseNotificationModel result = FirebaseNotificationModel();
    try {
      Map mapNotification = message["notification"];
      Map mapDataNotification = message['data'];

      String title = "";
      String body = "";
      String payload = "";

      if (Platform.isAndroid) {
        if (mapNotification != null && mapNotification.length != 0) {
          title = mapNotification["title"];
          body = mapNotification["body"];
          result = FirebaseNotificationModel.fromJson(mapDataNotification);

          result.title = title;
          result.body = body;
        }

        if (mapDataNotification != null && mapDataNotification.length != 0) {
          if (mapDataNotification["title"] != null && mapDataNotification["body"] != null) {
            // title = mapDataNotification["title"];
            // body = mapDataNotification["body"];
            // payload = mapDataNotification["news_id"];
            result = FirebaseNotificationModel.fromJson(mapDataNotification);
          }
        }
      } else if (Platform.isIOS) {
        if (mapNotification != null) {
          title = mapNotification["title"];
          body = mapNotification["body"];
          result.title = title;
          result.body = body;
        }

        // payload = message["news_id"];

        result = FirebaseNotificationModel.fromJson(message);
      }

      result.payload = jsonEncode(result);
    } catch (e) {
      print(e);
    }

    return result;
  }

  Future onSelectNotification(String payload) async {
    print("==> onSelectNotification");
    print(payload);
    // return Future<firebaseNotiData>;

    if (payload != null) {
      FirebaseNotificationModel data = FirebaseNotificationModel.fromJson(jsonDecode(payload));
      print(data.notiType);
      print(data.isGroupChat);

      // Navigator.of(context).popUntil((route) => route.isFirst);
      // if (!AppUtil.isNil(data?.notiType) && data.notiType.toUpperCase() == "CHAT") {
      //   if (!data.isGroupChat) {
      //     Navigator.push(
      //       context,
      //       MaterialPageRoute(
      //         builder: (context) => SingleChat(
      //           fullname: data.chatFullname,
      //           typeChat: data.typeChat,
      //           chatMasterId: data.chatMasterId,
      //           typeAccount: data.chatTypeAccount,
      //         ),
      //       ),
      //     );
      //   } else {
      //     Navigator.push(
      //       context,
      //       MaterialPageRoute(builder: (context) => GroupChat()),
      //     );
      //   }
      // } else if (!AppUtil.isNil(data?.notiType) && data.notiType.toUpperCase() == "NEWS") {
      //   if (!AppUtil.isNil(data?.notiTypeId)) {
      //     Navigator.push(
      //       context,
      //       MaterialPageRoute(builder: (context) => NewsDetail(id: data.notiTypeId)),
      //     );
      //   } else {
      //     Navigator.push(
      //       context,
      //       MaterialPageRoute(builder: (context) => NewsPage()),
      //     );
      //   }
      // } else if (!AppUtil.isNil(data?.notiType) && data.notiType.toUpperCase() == "PACKAGEREQUEST") {
      //   if (!AppUtil.isNil(data?.notiTypeId)) {
      //     context.read<AdditionalServiceDetailBloc>().add(
      //           AdditionalServiceDetailAddId(id: data.notiTypeId),
      //         );
      //     Navigator.push(
      //       context,
      //       MaterialPageRoute(builder: (context) => AdditionalServiceDetail()),
      //     );
      //   } else {
      //     Navigator.push(
      //       context,
      //       MaterialPageRoute(builder: (context) => AdditionalServicePage()),
      //     );
      //   }
      // } else if (!AppUtil.isNil(data?.notiType) && data.notiType.toUpperCase() == "ELECTRICPROBLEM") {
      //   Navigator.push(
      //     context,
      //     MaterialPageRoute(builder: (context) => ReportIncidentHistoryPage()),
      //   );
      // } else if (!AppUtil.isNil(data?.notiType) && data.notiType.toUpperCase() == "TIMELINE") {
      //   Navigator.push(
      //     context,
      //     MaterialPageRoute(builder: (context) => TimelinePage()),
      //   );
      // } else if (!AppUtil.isNil(data?.notiType) && data.notiType.toUpperCase() == "ACTIVITY") {
      //   Navigator.push(
      //     context,
      //     MaterialPageRoute(builder: (context) => ActivityPage()), //PackageOption
      //   );
      // } else {
      //   Navigator.push(
      //     context,
      //     MaterialPageRoute(builder: (context) => NotificationPage()),
      //   );
      // }
    }
  }

  _countNotification(String type) {
    // if (type.toUpperCase() == "NEWS") {
    //   context.read<NewsNotificationCountBloc>().add(
    //         NewsNotificationCountAddCount(),
    //       );
    // } else if (type.toUpperCase() == "ELECTRICPROBLEM") {
    //   context.read<ReportIncidentNotificationCountBloc>().add(
    //         ReportIncidentNotificationCountAddCount(),
    //       );
    // } else if (type.toUpperCase() == "PACKAGEREQUEST") {
    //   context.read<AdditionalServiceNotificationCountBloc>().add(
    //         AdditionalServiceNotificationCountAddCount(),
    //       );
    // } else if (type.toUpperCase() == "ACTIVITY") {
    //   context.read<ActivityNotificationCountBloc>().add(
    //         ActivityNotificationCountAddCount(),
    //       );
    // } else if (type.toUpperCase() == "TIMELINE") {
    //   context.read<TimelineNotificationCountBloc>().add(
    //         TimelineNotificationCountAddCount(),
    //       );
    // }

    // context.read<NotificationCountBloc>().add(
    //       NotificationCountAddCount(),
    //     );
  }
}

Future onDidReceiveLocalNotification(int id, String title, String body, String payload) async {
  print("==> onDidReceiveLocalNotification");
}
