import 'dart:async';

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:hamlemuhcrm/core/extensions/log_extension.dart';
import 'package:hamlemuhcrm/data/repo/home_repository.dart';
import 'package:hamlemuhcrm/features/calendar/view/calendar_view.dart';
import 'package:hamlemuhcrm/features/home/view/home_page.dart';
import 'package:hamlemuhcrm/features/human_resources/view/employee_page.dart';
import 'package:hamlemuhcrm/features/profile/view/profile_view.dart';
import 'package:hamlemuhcrm/features/projects/view/projects_page.dart';

import '../../../core/constants/app_constants.dart';
import '../../../core/constants/color_constants.dart';
import '../../../core/enum/user_enum.dart';
import '../../../core/init/application/application_init.dart';
import '../../../core/init/cache/cache_manager.dart';
import '../../../data/repo/notification_repository.dart';
import '../../customers/view/customers_page_view.dart';
import '../../message/view/message_view.dart';
import '../../notification/view/notification_view.dart';
import 'home_custom_state.dart';

class HomeCustomCubit extends Cubit<HomeState> {
  HomeCustomCubit() : super(HomeState.initial()) {
    startMessageService();
  }

  int cubitSecilenIndeks = 0;
  int cubitBodyIndeks = 0;
  int cubitBadgeCount = 0;

  String appBarText = ApplicationConstants.instance.homePageTxt;
  String musteriSayisi = '0';
  String personelSayisi = '0';
  int projeSayisi = 0;
  int gorevSayisi = 0;
  int ekGorevSayisi = 0;
  String getFcmTOKEN = '';

  final StreamController<RemoteMessage> _messageStreamController =
      StreamController<RemoteMessage>();

  Stream<RemoteMessage> get messageStream => _messageStreamController.stream;

  Future<Stream<RemoteMessage>> startListeningMessages() async {
    return messageStream;
  }

  final notificationRepo = NotificationRepository();

  Future<void> startMessageService() async {
    startListeningMessages();
    final messagging = FirebaseMessaging.instance;
    messagging.getToken().then((value) async {
      if (value != null && value.isNotEmpty) {
        getFcmTOKEN = value;
        value.log();
        await fcmTokenAddOrUpdate(value);
      }
    });

    FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
      // Bildirim içeriğini oluşturuyoruz.
      _messageStreamController.add(message);
      'mesaj yakalandı - base_cubit : ${message.notification?.body}'.log();
      startListeningMessages();

      AndroidNotificationDetails androidNotificationDetails =
          AndroidNotificationDetails(
        ApplicationInitialize.channel.id,
        ApplicationInitialize.channel.name,
        channelDescription: ApplicationInitialize.channel.description,
        color: ColorsConstants.instance.baseTheme,
        playSound: true,
        setAsGroupSummary: true,
        icon: '@mipmap/ic_launcher',
      );

      // Android bildirimini gösteriyoruz.
      ApplicationInitialize.flutterLocalNotificationsPlugin.show(
        message.hashCode,
        message.notification?.title,
        message.notification?.body,
        NotificationDetails(android: androidNotificationDetails),
      );
    });
  }

  Future<void> fcmTokenAddOrUpdate(String fcmtoken) async {
    final String token =
        await CacheManager.instance.getValue(UserEnum.token.toName);
    final String userfirmid =
        await CacheManager.instance.getValue(UserEnum.userfirmid.toName);
    final String loginid =
        await CacheManager.instance.getValue(UserEnum.loginid.toName);
    final result = await notificationRepo.fcmTokenAddOrUpdate(
        loginid, userfirmid, fcmtoken, token);
    if (result == null) {}
    switch (result!.success) {
      case 1:
        'fcm cevap : ${result.message} '.log();
      case 0:
        'fcm cevap : ${result.message} '.log();
      default:
    }
  }

  var pageList = [
    const Homepage(), //--------- index : 0 : anasayfa
    const ProjectsPage(), //----- index : 1 : projeler ve görevler
    const CalendarView(), //----- index : 2 : takvim sayfası
    const CustomersPageView(), // index : 3 : müşteriler & aktiviteler
    const ProfileView(), //------ index : 4 : profil sayfası
    const EmployeePage(), //----- index : 5 : personel listesi
    const NotificationView(), //- index : 6 : bildirimler sayfası
    const MessageView(), //------ index : 7 : mesajlar sayfası
  ];

  var repo = HomeRepository();

  Future<String> musteriSayisiGetir(
      String firmaEkleyenUserId,
      String kayitliFirma,
      String userTip,
      String token,
      String loginuserid) async {
    var data = await repo.musteriSayisi(
        firmaEkleyenUserId, kayitliFirma, userTip, token, loginuserid);
    musteriSayisi = data.firmaSayisi.toString();
    'musteri sayisi metotu çalıştı : $musteriSayisi'.log();
    if (musteriSayisi != '') {
      'musteri sayisi geldi'.log();
      return "1";
    } else {
      return "0";
    }
  }

  Future<String> personelSayisiGetir(String userUserfirmId, String userTip,
      String token, String loginuserid) async {
    var data =
        await repo.personelSayisi(userUserfirmId, userTip, token, loginuserid);
    personelSayisi = data.personelSayisi.toString();
    'personel sayisi metotu çalıştı : $musteriSayisi'.log();
    if (personelSayisi != '') {
      'personel sayisi geldi'.log();
      return "1";
    } else {
      return "0";
    }
  }

  Future<void> projeSayisiGetir(String token, String loginuserid) async {
    try {
      var data = await repo.projeSayisi(token, loginuserid);
      projeSayisi = data.projeSayisi!;
      gorevSayisi = data.gorevSayisi!;
      ekGorevSayisi = data.ekgorevSayisi!;
    } catch (e) {
      "Hata oluştu: $e".log();
    }
  }

  void changeAppBarText() {
    changeAppBarHeadlineTxt(cubitSecilenIndeks);
  }

  void setSecilenIndeks(int secilenIndex) async {
    cubitSecilenIndeks = secilenIndex;
    changeAppBarText();
    emit(state.copyWith(pageIndex: cubitSecilenIndeks));
  }

  void setSecilenBodyIndeks(int secilenIndex) async {
    cubitBodyIndeks = secilenIndex;
    changeAppBarHeadlineTxt(cubitBodyIndeks);
    emit(state.copyWith(pageIndex: cubitBodyIndeks));
  }

  void changeAppBarHeadlineTxt(int indexType) {
    if (indexType == 0) {
      appBarText = ApplicationConstants.instance.homePageTxt;
    } else if (indexType == 1) {
      appBarText = ApplicationConstants.instance.projectModuleTxt;
    } else if (indexType == 2) {
      appBarText = ApplicationConstants.instance.calendarModuleTxt;
    } else if (indexType == 3) {
      appBarText = ApplicationConstants.instance.customersModuleTxt;
    } else if (indexType == 4) {
      appBarText = ApplicationConstants.instance.profilePageTxt;
    } else if (indexType == 5) {
      appBarText = ApplicationConstants.instance.humanResourcesModuleTxt;
    } else if (indexType == 6) {
      appBarText = ApplicationConstants.instance.notificationPageTxt;
    } else if (indexType == 7) {
      appBarText = ApplicationConstants.instance.messageModuleTxt;
    } else if (indexType == 8) {
      appBarText = ApplicationConstants.instance.newsModuleTxt;
    }
  }

  Future<void> setBadgeCount(int pBadgeCount) async {
    emit(state.copyWith(isLoading: true, isComplete: false, isError: false));
    cubitBadgeCount = pBadgeCount;
    emit(state.copyWith(
        badgeCount: cubitBadgeCount,
        isLoading: false,
        isComplete: true,
        isError: false));
  }

  int get badgeCount => cubitBadgeCount;

  int get bodyindex => cubitBodyIndeks;
}
