import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import '../../data/models/gas_model.dart';
import '../../data/repository/appwrite_repository.dart';
import '../../pages/login/login_view.dart';
import '../../pages/tanklist/tanklist_view.dart';

import './widgets/map_view.dart' show MapDialogView;
import '../../data/repository/gasstation_repository.dart';

class GaslistController extends GetxController {
  final _dataBox = GetStorage('MyUserStorage');
  final szRxGasArt = 'DIE'.obs;
  //Gas Station Repository
  final GasStationRepository _gasStationRepository = GasStationRepository();
  final AppwriteRepository _authRepository = AppwriteRepository();
  final isLoadingList = false.obs;
  var gasStationsList = <GasModel>[].obs;

  @override
  void onInit() {
    loadListData();
    super.onInit();
  }

  @override
  void onReady() {}

  @override
  void onClose() {}

  Future<void> loadListData() async {
    isLoadingList(true);
    var lat = _dataBox.read('lastLatitude');
    var lng = _dataBox.read('lastLongitude');
    var gas = szRxGasArt.value;
    var result =
        await getGasStationsFromApi({'lat': lat, 'lng': lng, 'gas': gas});
    print('Gas Stations from API: $result');
    //Hier die Logik zum Laden der Daten einfügen
    gasStationsList.clear();
    gasStationsList.refresh();
    // add Map to GasModelList
    for (var element in result) {
      Map<String, dynamic> gasModelMap = (element as Map<String, dynamic>);
      var gasModelItem = GasModel.fromJson(gasModelMap);
      gasStationsList.add(gasModelItem);
    }
    //Simulate a delay for loading data

    isLoadingList(false);
    update();
  }

  Future<dynamic> getGasStationsFromApi(Map map) async {
    var result = await _gasStationRepository.getGasStationsLocations(map);
    return result;
  }

  void goToListView() {
    Get.offAndToNamed(TanklistPage.namedRoute);
  }

  Future<void> logoutSessionAndGoToLoginPage() async {
    // Handle logout logic here
    print('Logout session and go to login page');
    // Clear GetStorage session ID
    _dataBox.remove('sessionId');
    _dataBox.remove('userId');
    _dataBox.remove('userName');
    _dataBox.remove('userEmail');
    print('Session ID removed from GetStorage');
    await _authRepository.logout();
    Get.offAndToNamed(LoginPage.namedRoute);
  }

  Future<void> openDirectionMaps(double lat, double lng) async {
    Get.dialog(
      MapDialogView(
        latitude: lat,
        longitude: lng,
      ),
      barrierDismissible: true,
    );
  }
}
