
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:geolocator/geolocator.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/features/authentication/models/resp_models/authenticated_user_resp_model.dart';
import 'package:hmg_patient_app_new/services/analytics/flows/advance_payments.dart';
import 'package:hmg_patient_app_new/services/analytics/flows/app_nav.dart';
import 'package:hmg_patient_app_new/services/analytics/flows/appointments.dart';
import 'package:hmg_patient_app_new/services/analytics/flows/error_tracking.dart';
import 'package:hmg_patient_app_new/services/analytics/flows/hamburger_menu.dart';
import 'package:hmg_patient_app_new/services/analytics/flows/hmg_services.dart';
import 'package:hmg_patient_app_new/services/analytics/flows/live_care.dart';
import 'package:hmg_patient_app_new/services/analytics/flows/login_registration.dart';
import 'package:hmg_patient_app_new/services/analytics/flows/offers_promotions.dart';
import 'package:hmg_patient_app_new/services/analytics/flows/todo_list.dart';
import 'package:http/http.dart' as AnalyticEvents;


typedef GALogger = Function(String name, {Map<String, dynamic> parameters});

var _analytics = FirebaseAnalytics.instance;

_logger(String name, {Map<String, dynamic>? parameters}) async {
  // return;
  if (name.isNotEmpty) {
    if (name.contains(' ')) name = name.replaceAll(' ', '_');

    // To LowerCase
    if (parameters != null && parameters.isNotEmpty) {
      parameters = parameters.map((key, value) {
        final key_ = key.toLowerCase();
        var value_ = value;
        if (value is String) value_ = value.toLowerCase();
        return MapEntry(key_, value_);
      });
    }

    try {
      final safeParameters = parameters?.map((key, value) => MapEntry(key, value as Object));
      await _analytics.logEvent(
        name: name.trim().toLowerCase(),
        parameters: safeParameters,
      );
    } catch (e) {
      print('Error sending analytics event: $e');
    }

  }
}

class GAnalytics {
  static String? TREATMENT_TYPE;
  static String? APPOINTMENT_DETAIL_FLOW_TYPE;
  static String? PAYMENT_TYPE;

  setUser(AuthenticatedUser user) async {
    try {
      _analytics.setUserProperty(name: 'user_language', value: user.preferredLanguage == '1' ? 'arabic' : 'english');
      _analytics.setUserProperty(name: 'userid', value: Utils.generateMd5Hash(user.emailAddress!));
      _analytics.setUserProperty(name: 'login_status', value: user == null ? 'guest' : 'loggedin');
      // if (await PermissionService.isLocationEnabled()) {
      //   final location = await Geolocator.getCurrentPosition();
      //   if (location != null && !location.isMocked) {
      //     final places = await placemarkFromCoordinates(location.latitude, location.longitude,);
      //     final countryCode = places.first.isoCountryCode;
      //     _analytics.setUserProperty(name: 'user_country', value: countryCode);
      //   }
      // } else {
      //   _analytics.setUserProperty(name: 'user_country', value: "N/A");
      // }
    } catch (e) {}
  }

  // NavObserver navObserver() => NavObserver();
  final hamburgerMenu = HamburgerMenu(_logger);
  final bottomTabNavigation = AppNav(_logger);
  final hmgServices = HMGServices(_logger);
  final loginRegistration = LoginRegistration(_logger);
  final appointment = Appointment(_logger);
  final liveCare = LiveCare(_logger);
  final todoList = TodoList(_logger);
  final advancePayments = AdvancePayments(_logger);
  final offerPackages = OfferAndPromotion(_logger);
  final errorTracking = ErrorTracking(_logger);
}

// // adb shell setprop debug.firebase.analytics.app com.ejada.hmg -> Android
// class NavObserver extends RouteObserver<PageRoute<dynamic>> {
//   _sendScreenView(PageRoute route) async {
//     log(String className) {
//       var event = AnalyticEvents.get(className);
//       if (event.active != null) {
//         _analytics.setCurrentScreen(screenName: event.flutterName(), screenClassOverride: className).catchError(
//               (Object error) {
//             print('$FirebaseAnalyticsObserver: $error');
//           },
//           test: (Object error) {
//             return error is PlatformException;
//           },
//         );
//       }
//     }
//
//     if (route.settings.name != null && route.settings.name!.isNotEmpty && route.settings.name != "null") {
//       var class_ = routes[route.settings.name]!(0);
//       if (class_ != null) log(class_.toStringShort());
//     } else if (route is FadePage) {
//       var class_ = route.page;
//       if (class_ != null) log(class_.toStringShort());
//     } else if (route is MaterialPageRoute) {
//       var class_ = route.builder(route.subtreeContext!);
//       log(class_.toStringShort());
//     } else {
//       print("");
//     }
//   }
//
//   @override
//   void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
//     super.didPush(route, previousRoute);
//     if (route is PageRoute) {
//       _sendScreenView(route);
//     }
//   }
//
//   @override
//   void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
//     super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
//     if (newRoute is PageRoute) {
//       _sendScreenView(newRoute);
//     }
//   }
//
//   @override
//   void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
//     super.didPop(route, previousRoute);
//     // if (previousRoute is PageRoute && route is PageRoute) {
//     //   _sendScreenView(previousRoute);
//     // }
//   }
// }
