import 'package:appwrite/appwrite.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

import '../login/login_view.dart';
import '../graph/graph_view.dart';
import '../../data/models/tank_model.dart';
import '../../data/repository/appwrite_repository.dart';
import '../../pages/tank/tank_view.dart';
import '../../pages/gaslist/gaslist_view.dart';
import '../print/print_view.dart';

class TanklistController extends GetxController {
  final _dataBox = GetStorage('MyUserStorage');
  final isloadingList = false.obs;
  final rxTankListAlles = <AppWriteTankModel>[].obs;
  final rxTankListActualYear = <AppWriteTankModel>[].obs;
  final szRxUserId = 'NoUser'.obs;
  //AppWrite API-REST get Data
  final AppwriteRepository _authRepository = AppwriteRepository();
  final szRxYear = DateTime.now().year.obs.toString().obs;
  final szRxSummeYearLiter = '0.0'.obs;
  final szRxSummePrice = '0.0'.obs;

  @override
  void onInit() {
    szRxUserId(_dataBox.read('userId'));
    super.onInit();
  }

  @override
  void onReady() {
    getTankList();
    super.onReady();
  }

  @override
  void onClose() {}

  Future<void> getTankList() async {
    isloadingList(true);
    bool isErrorByLoading = false;
    String message = '';
    try {
      await _authRepository
          .listTankStops(szRxUserId.value)
          .then((tankListData) {
        if (tankListData.documents.isEmpty) {
          isErrorByLoading = false;
          message = 'Leere Liste keine Daten vorhanden';
          isloadingList(false);
          rxTankListAlles.clear();
          rxTankListActualYear.clear();
          szRxSummeYearLiter('0.0');
          szRxSummePrice('0.0');
          update();
          return;
        }
        rxTankListAlles.clear();
        var data = tankListData.toMap();
        List d = data['documents'].toList();
        rxTankListAlles.value =
            d.map((e) => AppWriteTankModel.fromMap(e['data'])).toList();
        rxTankListAlles.sort((a, b) {
          final DateTime dateA = DateTime.parse(a.date);
          final DateTime dateB = DateTime.parse(b.date);
          return dateB.compareTo(dateA);
        });
        //Tank List per Actual year**********
        rxTankListActualYear.clear();
        rxTankListActualYear.value = rxTankListAlles
            .where((tank) => tank.date.startsWith(szRxYear.value))
            .toList();
        // rxTankListActualYear.value = rxTankListAlles;
        //Summe Liter aktuelles Jahr*********
        szRxSummeYearLiter(
            rxTankListActualYear.fold<double>(0.0, (previousValue, element) {
          return previousValue + (double.tryParse(element.liters) ?? 0.0);
        }).toStringAsFixed(2));
        //Summe Preis aktuelles Jahr*********
        szRxSummePrice(
            rxTankListActualYear.fold<double>(0.0, (previousValue, element) {
          return previousValue +
              (double.tryParse(element.szSummePreis!) ?? 0.0);
        }).toStringAsFixed(2));
        message = 'Liste wurde erfolgreich geladen';
        isErrorByLoading = false;
      }).catchError((error) {
        isErrorByLoading = true;
        if (error is AppwriteException) {
          message = error.message!;
        } else {
          message = 'Uuups da ist was schief gelaufen';
        }
      });
    } catch (e) {
      isErrorByLoading = true;
      message = 'Fehler beim Laden der Tankliste';
      print('Error fetching tank list: $e');
    } finally {
      if (!isErrorByLoading) {
        isloadingList(false);
      }
    }
    String title = isErrorByLoading ? 'Fehler' : 'Erfolg';
    print('$title: $message');
    update();
  }

  void goToUpdatePage(AppWriteTankModel item) {
    var map = item.toMap();
    print('Go to Update Page with data: $map');
    // Go to Update Page
    Get.offAndToNamed(TankPage.namedRoute,
        arguments: {'from': 'Update', 'data': map});
  }

  void goToInputPage() {
    Get.offAndToNamed(TankPage.namedRoute, arguments: {'from': 'Input'});
  }

  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);
  }

  void goToChartView() {
    Get.offAndToNamed(GraphPage.namedRoute);
  }

  void deleteTankStop(String documentId) async {
    bool isErrorByLoading = false;
    String message = '';
    try {
      await _authRepository.deleteTankStop(documentId).then((response) async {
        await getTankList();
        message = 'Tankstopp wurde erfolgreich gelöscht';
      }).catchError((error) {
        isErrorByLoading = true;
        if (error is AppwriteException) {
          message = error.message!;
        } else {
          message = 'Uuups da ist was schief gelaufen';
        }
      });
    } catch (e) {
      isErrorByLoading = true;
      message = 'Fehler beim Löschen des Tankstopps';
      print('Error deleting tank stop: $e');
    }
    String title = isErrorByLoading ? 'Fehler' : 'Erfolg';
    print('$title: $message');
  }

  Future<void> goToGasView() async {
    //Go to Gas Station List Page
    await Get.offAndToNamed(GaslistPage.namedRoute);

  }

  void goToPrintView() {
        
    List<Map<String, dynamic>> tankMap = rxTankListActualYear.map((e) => e.toMap()).toList();
    Get.offAndToNamed(PrintPage.namedRoute, arguments: {
      'tankList': tankMap,
      'year': szRxYear.value,
      'summeLiter': szRxSummeYearLiter.value,
      'summePreis': szRxSummePrice.value,
    });
  }
}
