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

import 'package:easy_localization/easy_localization.dart';
import 'package:gms_check/gms_check.dart';
import 'package:hmg_patient_app_new/core/common_models/privilege/HMCProjectListModel.dart';
import 'package:hmg_patient_app_new/core/common_models/privilege/ProjectDetailListModel.dart';
import 'package:hmg_patient_app_new/core/common_models/privilege/VidaPlusProjectListModel.dart';
import 'package:hmg_patient_app_new/features/authentication/models/resp_models/authenticated_user_resp_model.dart';
import 'package:hmg_patient_app_new/features/authentication/models/resp_models/check_user_staus_nhic_response_model.dart';
import 'package:hmg_patient_app_new/features/authentication/models/resp_models/select_device_by_imei.dart';
import 'package:hmg_patient_app_new/services/navigation_service.dart';
import 'package:hmg_patient_app_new/services/cache_service.dart';

import '../features/authentication/models/request_models/registration_payload_model.dart';

class AppState {
  NavigationService navigationService;
  CacheService cacheService;

  static const String _profileImageKey = 'profile_image_data';

  AppState({required this.navigationService, required this.cacheService}){
    checkIfGMSAvailableOrNot();
    _loadProfileImageFromCache();
  }

  bool isEnabledOffersAndDiscountsCarousel = false;

  double userLat = 0.0;

  set setUserLat(v) => userLat = v;

  double userLong = 0.0;

  set setUserLong(v) => userLong = v;

  bool isArabic() => EasyLocalization.of(navigationService.navigatorKey.currentContext!)?.locale.languageCode == "ar";

  int getLanguageID() => EasyLocalization.of(navigationService.navigatorKey.currentContext!)?.locale.languageCode == "ar" ? 1 : 2;

  int getDeviceTypeID() => Platform.isIOS ? 1 : 2;

  String? getLanguageCode() => EasyLocalization.of(navigationService.navigatorKey.currentContext!)?.locale.languageCode;

  AuthenticatedUser? _authenticatedRootUser;
  AuthenticatedUser? _authenticatedChildUser;

  bool isPaytabsEnabled = false;
  bool isPayfortHostedPageEnabled = true;

  void setIsPaytabsEnabled(bool value) {
    isPaytabsEnabled = value;
    // isPaytabsEnabled = true;
  }

  void setIsPayfortHostedPageEnabled(bool value) {
    isPayfortHostedPageEnabled = value;
    // isPayfortHostedPageEnabled = false;
  }

  int? _superUserID;
  bool isChildLoggedIn = false;
  bool isGMSAvailable = true;
  bool isAndroid = true;
  bool isRatedVisible =false;
  void setAuthenticatedUser(AuthenticatedUser? authenticatedUser, {bool isFamily = false}) {
    if (isFamily) {
      _authenticatedChildUser = authenticatedUser;
    } else {
      setIsAuthenticated = true;
      _authenticatedRootUser = authenticatedUser;
    }
  }

  FutureOr<void> checkIfGMSAvailableOrNot() async {
    isGMSAvailable = (await GmsCheck().checkGmsAvailability()) ?? true;
    if(Platform.isIOS) {
       isGMSAvailable = true;
       isAndroid = false;
       return;
    }
  }

  AuthenticatedUser? getAuthenticatedUser({bool isFamily = false}) {
    if (isFamily) {
      return _authenticatedChildUser;
    } else {
      return _authenticatedRootUser;
    }
  }

  int? get getSuperUserID => _superUserID;

  bool get getIsChildLoggedIn => isChildLoggedIn;

  set setSuperUserID(int? value) => _superUserID = value;

  set setIsChildLoggedIn(bool value) => isChildLoggedIn = value;

  String _userBloodGroup = "";

  String get getUserBloodGroup => _userBloodGroup;

  set setUserBloodGroup(String value) => _userBloodGroup = value;

  String? _profileImageData;

  String? get getProfileImageData => _profileImageData;

  set setProfileImageData(String? value) {
    // Clear old data first
    if (_profileImageData != null && _profileImageData != value) {
      print('🔄 Replacing profile image: old data length=${_profileImageData!.length}, new data length=${value?.length ?? 0}');
    }

    // Set new value directly WITHOUT caching
    _profileImageData = value;

    if (value != null && value.isNotEmpty) {
      print('✅ Profile image set (length: ${value.length}) - NO CACHE');
    } else {
      print('🗑️ Profile image cleared - NO CACHE');
    }
  }

  /// Load profile image from cache on app initialization - DISABLED
  void _loadProfileImageFromCache() {
    // DO NOT LOAD FROM CACHE - always fetch fresh from API
    _profileImageData = null;
    print('📂 Profile image cache disabled - will fetch from API');
  }

  /// Clear profile image data (e.g., on logout or user switch)
  void clearProfileImageCache() {
    print('🧹 Clearing profile image data (was: ${_profileImageData != null ? "${_profileImageData!.length} chars" : "null"})');
    _profileImageData = null;
    print('✅ Profile image data cleared - NO CACHE');
  }

  SelectDeviceByImeiRespModelElement? _selectDeviceByImeiRespModelElement;

  void setSelectDeviceByImeiRespModelElement(SelectDeviceByImeiRespModelElement? value) {
    _selectDeviceByImeiRespModelElement = value;
  }

  SelectDeviceByImeiRespModelElement? get getSelectDeviceByImeiRespModelElement => _selectDeviceByImeiRespModelElement;

  // String appLoginTokenID = "";
  //
  // set setAppLoginTokenID(v) => appLoginTokenID = v;

  String deviceToken = "";

  set setDeviceToken(v) => deviceToken = v;

  String voipToken = "";

  set setVoipToken(v) => voipToken = v;

  String appAuthToken = "";

  set setAppAuthToken(v) => appAuthToken = v;

  String sessionId = "";

  set setSessionId(v) => sessionId = v;

  bool isAuthenticated = false;

  set setIsAuthenticated(v) => isAuthenticated = v;


  String deviceTypeID = "";

  set setDeviceTypeID(v) => deviceTypeID = v;

  String _familyFileTokenID = "";

  String get getFamilyFileTokenID => _familyFileTokenID;

  set setFamilyFileTokenID(String value) {
    _familyFileTokenID = value;
  }

  List<VidaPlusProjectListModel> vidaPlusProjectList = [];
  List<ListPrivilege> privilegeModelList = [];
  List<HMCProjectListModel> hMCProjectListModel = [];
  List<ProjectDetailListModel> projectDetailListModel = [];

  setVidaPlusProjectList(List<VidaPlusProjectListModel> vidaPlusProjectListModelInput) {
    vidaPlusProjectList = vidaPlusProjectListModelInput;
  }

  setPrivilegeModelList(List<ListPrivilege> privilegeModelListInput) {
    privilegeModelList = privilegeModelListInput;
  }

  setHMCProjectList(List<HMCProjectListModel> hMCProjectListModelInput) {
    hMCProjectListModel = hMCProjectListModelInput;
  }

  setProjectsDetailList(List<ProjectDetailListModel> projectDetailListModelInput) {
    projectDetailListModel = projectDetailListModelInput;
  }

  CheckUserStatusResponseNHIC? _nHICUserData;

  CheckUserStatusResponseNHIC get getNHICUserData => _nHICUserData!;

  set setNHICUserData(CheckUserStatusResponseNHIC value) {
    _nHICUserData = value;
  }

  RegistrationDataModelPayload? _userRegistrationPayload;

  RegistrationDataModelPayload get getUserRegistrationPayload => _userRegistrationPayload ?? RegistrationDataModelPayload();

  set setUserRegistrationPayload(RegistrationDataModelPayload value) {
    _userRegistrationPayload = value;
  }

  ///this will be called if there is any problem in getting the user location
  void resetLocation() {
    userLong = 0.0;
    userLat = 0.0;
  }

   setRatedVisible(bool value) {
    isRatedVisible = value;
  }

  Map<String, dynamic> _userSwitchPayloads = {};
  int _childSwitchCounter = 0;

  Map<String, dynamic> get getUserSwitchPayloads => _userSwitchPayloads;

  void addUserSwitchPayload(dynamic payload, {bool isSuperUser = false}) {
    var patientID = payload is Map ? payload['patientid'] : null;

    if (patientID == null) {
      if (isSuperUser) {
        _userSwitchPayloads['superUser'] = payload;
        _childSwitchCounter = 0;
      } else {
        _childSwitchCounter++;
        if (_childSwitchCounter == 1) {
          _userSwitchPayloads['child'] = payload;
        } else {
          _userSwitchPayloads['child$_childSwitchCounter'] = payload;
        }
      }
      return;
    }

    String? existingKey;
    for (var entry in _userSwitchPayloads.entries) {
      if (entry.value is Map && entry.value['PatientID'] == patientID) {
        existingKey = entry.key;
        break;
      }
    }

    if (isSuperUser) {
      if (existingKey != null && existingKey != 'superUser') {
        _userSwitchPayloads.remove(existingKey);
      }
      _userSwitchPayloads['superUser'] = payload;
      _childSwitchCounter = 0;
    } else {
      if (existingKey != null) {
        _userSwitchPayloads[existingKey] = payload;
      } else {
        _childSwitchCounter++;
        if (_childSwitchCounter == 1) {
          _userSwitchPayloads['child'] = payload;
        } else {
          _userSwitchPayloads['child$_childSwitchCounter'] = payload;
        }
      }
    }
  }


  dynamic getUserSwitchPayload({required String userType}) {
    return _userSwitchPayloads[userType];
  }

  dynamic getUserSwitchPayloadByIndex({bool isSuperUser = false, int? childIndex}) {
    if (isSuperUser) {
      return _userSwitchPayloads['superUser'];
    } else if (childIndex != null) {
      if (childIndex == 1) {
        return _userSwitchPayloads['child'];
      } else {
        return _userSwitchPayloads['child$childIndex'];
      }
    }
    return null;
  }

  void clearUserSwitchPayloads() {
    _userSwitchPayloads.clear();
    _childSwitchCounter = 0;
  }

  void clearChildUsersKeepSuperUser() {
    // Keep the super user payload
    final superUserPayload = _userSwitchPayloads['superUser'];
    
    // Clear all payloads
    _userSwitchPayloads.clear();
    _childSwitchCounter = 0;
    
    // Restore super user if it existed
    if (superUserPayload != null) {
      _userSwitchPayloads['superUser'] = superUserPayload;
    }
  }
}
