import 'package:bloc/bloc.dart';
import 'package:e_commerce_training/src/model/preference/app_preference.dart';
import 'package:e_commerce_training/src/model/repository/app_repository.dart';
import 'package:e_commerce_training/src/model/response/notification_response.dart';
import 'package:e_commerce_training/src/model/service/api_result.dart';
import 'package:e_commerce_training/src/model/service/network_exceptions.dart';
import 'package:e_commerce_training/src/util/const.dart';
import 'package:e_commerce_training/src/util/logger.dart';
import 'package:e_commerce_training/src/util/util.dart';
import 'package:equatable/equatable.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

part 'notification_state.dart';

class NotificationCubit extends Cubit<NotificationState> {
  List<NotificationData> listNotification = [];
  final AppRepository repository;
  late FlutterLocalNotificationsPlugin fltNotification;
  int _currentPage = 1;
  bool hasMorePage = true;

  int get currentPage => _currentPage;

  String? get token => appPreference.getData(Const.TOKEN);

  String? get deviceToken => appPreference.getData(Const.DEVICE_TOKEN);

  bool get isLoggedIn => !Util.isEmpty(token);

  NotificationCubit(this.repository) : super(NotificationInitial());
  FirebaseMessaging messaging = FirebaseMessaging.instance;
  void pushFCMtoken() async {
    String? token = await messaging.getToken();
    print(token);
//you will get token here in the console
  }

  void getListNotification({bool isRefresh = false, bool isLoadMore = false}) async {
    emit((!isRefresh && !isLoadMore) ? NotificationLoading() : NotificationInitial());
    if (isRefresh) _currentPage = 1;
    if (isLoadMore) {
      _currentPage++;
    }
    if (listNotification.length < Const.DEFAULT_SIZE) {
      hasMorePage = false;
    }
    ApiResult<NotificationResponse> notificationResult =
        await repository.getListNotification(pageNumber: _currentPage, deviceToken: deviceToken, userToken: token);
    notificationResult.when(success: (NotificationResponse response) async {
      listNotification = response.data ?? [];
      emit(GetNotificationSuccess());
    }, failure: (NetworkExceptions error) async {
      emit(NotificationFailure(NetworkExceptions.getErrorMessage(error)));
      try {
        NotificationResponse notificationResponse = NotificationResponse.fromJson(await Util.parseJson("notification.json"));
        listNotification = notificationResponse.data ?? [];
        emit(GetNotificationSuccess());
      } catch (e) {
        logger.e(e);
      }
    });
  }

  void readNotification(NotificationData notification) {
    emit(NotificationLoading());
    if (notification.isRead != true) {
      notification.isRead = true;
      if (notification.id != null) repository.updateNotification(notification.id!);
      emit(ReadNotificationSuccess());
    } else {
      emit(NotificationInitial());
    }
  }

  void initMessaging() {
    var androidInit = const AndroidInitializationSettings("@mipmap/ic_launcher");
    var iosInit = const IOSInitializationSettings();
    var initSetting = InitializationSettings(android: androidInit, iOS: iosInit);
    fltNotification = FlutterLocalNotificationsPlugin();
    fltNotification.initialize(initSetting);
    var androidDetails = const AndroidNotificationDetails("1", "hannelName", "channel Description");
    var iosDetails = const IOSNotificationDetails();
    var generalNotificationDetails = NotificationDetails(android: androidDetails, iOS: iosDetails);
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      RemoteNotification? notification = message.notification;
      AndroidNotification? android = message.notification?.android;
      if (notification != null && android != null) {
        fltNotification.show(notification.hashCode, notification.title, notification.body, generalNotificationDetails);
      }
    });
  }
}
