import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/cupertino.dart';
import 'package:hmg_patient_app_new/core/dependencies.dart';
import 'package:hmg_patient_app_new/core/location_util.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/features/weather/models/waether_cities_model.dart';
import 'package:hmg_patient_app_new/features/weather/weather_repo.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/services/error_handler_service.dart';
import 'package:hmg_patient_app_new/services/navigation_service.dart';
import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart';
import 'package:permission_handler/permission_handler.dart' show openAppSettings;

import '../../core/app_state.dart' show AppState;

class WeatherMonitorViewModel extends ChangeNotifier {
  WeatherRepo weatherRepo;
  ErrorHandlerService errorHandlerService;
  LocationUtils locationUtils;
  bool isLocationAvailable =  false;

  WeatherMonitorViewModel({required this.weatherRepo, required this.errorHandlerService, required this.locationUtils});

  final List<GetCityInfoList> _cityInfoList = [];
  bool isLoading = false;
  bool isWeatherNeedToLoad = true;

  List<GetCityInfoList> get cityInfoList => _cityInfoList;

  Future<void> fetchCityInfoList({Function(dynamic)? onSuccess, Function(String)? onError}) async {
    if (!isWeatherNeedToLoad) {
      return;
    }
    isLoading = true;
    notifyListeners();
    _cityInfoList.clear();

    // Check if location permission is already granted
    final isLocationEnabled = await locationUtils.isLocationPermissionEnabled();

    if (isLocationEnabled && getIt.get<AppState>().userLat != 0.0 && getIt.get<AppState>().userLong != 0.0) {
      // Permission already granted, fetch data directly
      isLocationAvailable = true;
      final result = await weatherRepo.getCityInfo();
      result.fold(
        (failure) async {
          isLoading = false;
          notifyListeners();
          await errorHandlerService.handleError(failure: failure);
          if (onError != null) {
            onError(failure.toString());
          }
        },
        (apiResponse) {
          isLoading = false;
          if (apiResponse.messageStatus == 2) {
            notifyListeners();
            if (onError != null) {
              onError(apiResponse.errorMessage ?? "Unknown error");
            }
          } else if (apiResponse.messageStatus == 1) {
            final cities = apiResponse.data ?? [];
            _cityInfoList.addAll(cities);
            notifyListeners();
            if (onSuccess != null) {
              onSuccess(apiResponse);
            }
            isWeatherNeedToLoad = false;
          }
        },
      );
    } else {
      // Permission not granted, request it
      locationUtils.isShowConfirmDialog = true;
      locationUtils.getLocation(
          isShowConfirmDialog: true,
          onFailure: (){
            isLoading = false;
            notifyListeners();
            showCommonBottomSheetWithoutHeight(
              title: LocaleKeys.notice.tr(),
              getIt.get<NavigationService>().navigatorKey.currentContext!,
              child: Utils.getWarningWidget(
                  loadingText: LocaleKeys.grantLocationPermission.tr(),
                  isShowActionButtons: true,
                  onCancelTap: () {
                    getIt.get<NavigationService>().pop();
                  },
                  onConfirmTap: () async {
                    getIt.get<NavigationService>().pop();
                    openAppSettings();
                  }),
              callBackFunc: () {},
              isFullScreen: false,
              isCloseButtonVisible: true,
            );
          },
          onSuccess: (position) async {
            isLocationAvailable = true;
            final result = await weatherRepo.getCityInfo();
            result.fold(
              (failure) async {
                isLoading = false;
                notifyListeners();
                await errorHandlerService.handleError(failure: failure);
                if (onError != null) {
                  onError(failure.toString());
                }
              },
              (apiResponse) {
                isLoading = false;
                if (apiResponse.messageStatus == 2) {
                  notifyListeners();
                  if (onError != null) {
                    onError(apiResponse.errorMessage ?? "Unknown error");
                  }
                } else if (apiResponse.messageStatus == 1) {
                  final cities = apiResponse.data ?? [];
                  _cityInfoList.addAll(cities);
                  notifyListeners();
                  if (onSuccess != null) {
                    onSuccess(apiResponse);
                  }
                }
              },
            );
          });
    }
  }

  Future<bool> checkIfTheLocationIsEnabledOrNot() async {
    bool value =  await locationUtils.isLocationPermissionEnabled();
    isLocationAvailable = value;
    notifyListeners();
    return value;

  }

  void initiateFetchWeather() async  {
    if(await checkIfTheLocationIsEnabledOrNot()){
      fetchCityInfoList();
    }
  }
}
