// ignore_for_file: unnecessary_overrides, unrelated_type_equality_checks

import 'dart:io';

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter/material.dart' as td;
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:logger/logger.dart';
import 'package:overlay_support/overlay_support.dart';
import 'package:IQ/app/global/static_informs.dart';
import 'package:IQ/app/modules/home/models/notifications_model.dart';
import 'package:IQ/app/modules/home/providers/dashboard.dart';
import 'package:IQ/app/modules/home/providers/language_currency.dart';
import 'package:IQ/app/modules/home/providers/notifications.dart';
import 'package:IQ/app/modules/home/providers/service.dart';
import 'package:IQ/app/modules/home/providers/user.dart';

String? mtoken = "";

class HomeController extends GetxController with WidgetsBindingObserver {
  final GlobalKey<ScaffoldState> key = GlobalKey();
  int current = 0;
  final slidersImages = [
    "https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
    "https://www.whoa.in/201604-Whoa/-natural-wallpaper-ultra-hd-4k-images-wallpapers.jpg",
    "https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
    "https://www.whoa.in/201604-Whoa/-natural-wallpaper-ultra-hd-4k-images-wallpapers.jpg",
    "https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
    "https://www.whoa.in/201604-Whoa/-natural-wallpaper-ultra-hd-4k-images-wallpapers.jpg",
  ];
  onPageChanged(index, _) {
    current = index;
    update();
  }

  ///
  late final FirebaseMessaging _messaging;
  PushNotification? notificationInfo;
  Future<void> _firebaseMessagingBackgroundHandler(
      RemoteMessage message) async {}

  void registerNotification() async {
    // 2. Instantiate Firebase Messaging
    _messaging = FirebaseMessaging.instance;

    FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

    // 3. On iOS, this helps to take the user permissions
    NotificationSettings settings = await _messaging.requestPermission(
      alert: true,
      badge: true,
      provisional: false,
      sound: true,
    );

    if (settings.authorizationStatus == AuthorizationStatus.authorized) {
      // For handling the received notifications
      FirebaseMessaging.onMessage.listen((RemoteMessage message) {
        // Parse the message received
        PushNotification notification = PushNotification(
          title: message.notification?.title,
          body: message.notification?.body,
        );

        notificationInfo = notification;
        update();

        if (notificationInfo != null) {
          // For displaying the notification as an overlay
          showSimpleNotification(
            Text(notificationInfo!.title!),
            subtitle: Text(notificationInfo!.body!),
            background: Colors.cyan.shade700,
            duration: const Duration(seconds: 2),
          );
        }
      });
    } else {}
  }

// For handling notification when the app is in terminated state
  checkForInitialMessage() async {
    await FirebaseMessaging.instance.getToken().then((token) {
      Logger().e("token : $token");
      mtoken = token;
    });

    RemoteMessage? initialMessage =
        await FirebaseMessaging.instance.getInitialMessage();

    if (initialMessage != null) {
      PushNotification notification = PushNotification(
        title: initialMessage.notification?.title,
        body: initialMessage.notification?.body,
      );
      notificationInfo = notification;
      update();
    }
  }

  //
  String remainingDays = dashboard?.data?.remainingDays ?? '';
  String remainingIcon = "assets/home_icons/remaining_days.svg";
  String? profileName = service?.data?.profileName ?? ' . . . ';
  String fullName =
      '${user?.data?.firstname ?? ""} ${user?.data?.lastname ?? ""}';
  String loginName = '${user?.data?.username}';
  String subscriptionPrice = '';
  String expireDate =
      '${service?.data?.expiration?.split(' ')[1]} ${service?.data?.expiration?.split(' ')[0]}';

  int? remainingTraffic = dashboard?.data?.remainingTraffic;

  String availableBalance =
      '${languagesCurrencyModel?.data?.currency ?? ''} ${dashboard?.data?.balance}';

  ///
  String connectionIcon = "assets/home_icons/connected.svg";
  String connectionStatusText = 'connectionStatusText'.tr;
  String? floatButtonActivation;
  String activiationIcon = "assets/home_icons/active.svg";
  String activiationStatusText = 'activiationStatusText'.tr;

  activationStatus() {
    final oCcy = NumberFormat.currency(
      locale: 'ar',
      customPattern: '#,### \u00a4',
      decimalDigits: 0,
      symbol: '${languagesCurrencyModel?.data?.currency}',
    );
    remainingDays = dashboard?.data?.remainingDays ?? '';
    remainingIcon = "assets/home_icons/remaining_days.svg";
    profileName = service?.data?.profileName ?? ' . . . ';
    fullName = '${user?.data?.firstname ?? ""} ${user?.data?.lastname ?? ""}';
    loginName = '${user?.data?.username}';

    subscriptionPrice = oCcy.format(service?.data?.price);
    expireDate =
        '${service?.data?.expiration?.split(' ')[1]} ${service?.data?.expiration?.split(' ')[0]}';
    availableBalance =
        '${languagesCurrencyModel?.data?.currency ?? ''} ${dashboard?.data?.balance}';
    remainingTraffic = dashboard?.data?.remainingTraffic;

    if (dashboard?.data?.remainingDays != '') {
      if (dashboard?.data?.remainingDays != '0') {
        remainingDays = dashboard?.data?.remainingDays ?? '!';
      } else {
        remainingDays = '!';
      }
    } else {
      remainingDays = '!';
    }
    if (service?.data?.status != null) {
      if (service?.data?.status == true) {
        connectionIcon = "assets/home_icons/connected.svg";
        connectionStatusText = 'connectionStatusText'.tr;
      } else {
        connectionIcon = "assets/home_icons/disconnected.svg";
        connectionStatusText = 'connectionStatusTextOffiline'.tr;
      }
    } else {
      connectionIcon = "assets/home_icons/disconnected.svg";
      connectionStatusText = 'connectionStatusTextOffiline'.tr;
    }
    if (service?.data?.subscriptionStatus?.status != null) {
      if (service?.data?.subscriptionStatus?.status == true) {
        activiationIcon = "assets/home_icons/active.svg";
        activiationStatusText = 'activiationStatusTextactive'.tr;
        floatButtonActivation = '!floatButtonActivation'.tr;
      } else {
        activiationIcon = "assets/home_icons/unactive.svg";
        activiationStatusText = 'activiationStatusText'.tr;
        floatButtonActivation = 'floatButtonActivation'.tr;
      }
    } else {
      activiationIcon = "assets/home_icons/unactive.svg";
      activiationStatusText = 'activiationStatusTextactive'.tr;
      floatButtonActivation = 'floatButtonActivation'.tr;
    }
    update();
  }

  Future<void> onRefresh() async {
    dashboard = null;
    user = null;
    service = null;
    languagesCurrencyModel = null;
    fetchHomeData = false;
    notifications = null;
    fetchLoadingHomeDataVar = fetchLoadingHomeData();
    update();
  }

// ignore: prefer_typing_uninitialized_variables
  var fetchLoadingHomeDataVar;
  bool fetchHomeData = false;
  fetchLoadingHomeData() async {
    await getLanguageCurrencyInforms();
    await getUserDashboardInforms();
    await getUserNotificationsInforms("/2");
    await getUserServiceInforms();
    await getUserInforms();
    if (getUserDashboardInformsLoads &&
        getUserServiceInformsLoads &&
        getUserInformsLoads &&
        getUserNotificationsInformsLoads) {
      activationStatus();
      fetchHomeData = true;
      update();
    }
  }

  ///
  List<Data>? listOfNotification = notifications?.data;

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.inactive ||
        state == AppLifecycleState.detached ||
        state == AppLifecycleState.paused) return;
    if (state == AppLifecycleState.resumed) {
      defaultLocale = Platform.localeName.split('_')[0];
      textDirection =
          defaultLocale != "en" ? td.TextDirection.ltr : td.TextDirection.rtl;
      snackBarText = 'back_twice'.tr;
      onRefresh();
    }
  }

  @override
  @override
  void onInit() {
    fetchLoadingHomeDataVar = fetchLoadingHomeData();
    WidgetsBinding.instance.addObserver(this);
    registerNotification();
    checkForInitialMessage();
    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      PushNotification notification = PushNotification(
        title: message.notification?.title,
        body: message.notification?.body,
      );
      notificationInfo = notification;
      update();
    });
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    WidgetsBinding.instance.removeObserver(this);
  }
}

class PushNotification {
  PushNotification({
    this.title,
    this.body,
  });
  String? title;
  String? body;
}
