import 'package:flutter_tank_web_app/pages/gasstations_view.dart';
import 'package:get/get.dart';

import '../models/tank_model.dart';
import '../pages/detail_view.dart';
import '../pages/edit_view.dart';
import '../services/appwrite_service.dart';
import '../pages/graph_view.dart';

class HomeController extends GetxController {
  final isLoading = false.obs;
  final listTankModel = <TankModel>[].obs;
  final appwriteService = AppwriteService();
  final currentYear = DateTime.now().year.obs;

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

  @override
  void onReady() {}

  @override
  void onClose() {}

  void changeYear(int year) {
    currentYear.value = year;
    _loadListDocument();
    update();
  }

  Future<void> _loadListDocument() async {
    isLoading.value = true;
    if (listTankModel.isNotEmpty) {
      listTankModel.clear();
    }
    var userId = await appwriteService.getCurrentUserId();
    if (userId == null) {
      //User nicht eingeloggt, evtl. zur Login-Seite navigieren
      update();
      return;
    }
    var resultList = await appwriteService.getDocumentsFromCollection(userId);
    if (resultList.isEmpty) {
      //Dokumente erfolgreich geladen, hier können Sie die Liste verarbeiten
      print('Dokumente wurden nicht geladen: ${resultList.length}');
    } else {
      for (var doc in resultList) {
        var tankModel = TankModel.fromMap(doc.data);
        listTankModel.add(tankModel);
      }
      if (listTankModel.isNotEmpty) {
        var sortList = listTankModel.where((tank) {
          var year = (DateTime.tryParse(tank.szDate)!).year;
          return year == currentYear.value;
        }).toList();
        listTankModel.clear();
        listTankModel.addAll(sortList);
        listTankModel.sort((a, b) {
          var dateA = DateTime.tryParse(a.szDate)!;
          var dateB = DateTime.tryParse(b.szDate)!;
          return dateB.compareTo(dateA);
        });
        for (var tank in listTankModel) {
          print(
            'SortTankModel: ${tank.szDate} - ${tank.szLiters}L - ${tank.szPricePerLiter}€/L - Total: ${tank.szPriceTotal}€',
          );
        }
      }
    }
    isLoading.value = false;
    update();
  }

  Future<void> logout() async {
    var logoutSuccess = await appwriteService.logout();
    if (logoutSuccess) {
      Get.snackbar(
        'Logout erfolgreich',
        'Sie wurden abgemeldet.',
        snackPosition: SnackPosition.BOTTOM,
      );
      Get.offAllNamed('/login-page');
    } else {
      Get.snackbar(
        'Logout fehlgeschlagen',
        'Bitte versuchen Sie es erneut.',
        snackPosition: SnackPosition.BOTTOM,
      );
    }
  }

  Future<void> viewTankDetails(TankModel tank) async {
    var result = await Get.toNamed(DetailPage.namedRoute, arguments: tank);
    if (result == 'deleted') {
      _loadListDocument();
    }
  }

  Future<void> navigateToAddTankEntry() async {
    await Get.offAllNamed(EditPage.namedRoute);
  }

  void goToGraphPage() {
    Get.toNamed(GraphPage.namedRoute, arguments: listTankModel);
  }

  void goToGasStations() {
    Get.toNamed(GasstationsPage.namedRoute);
  }
}
