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

import '../../data/models/tank_model.dart';
import '../../data/repository/appwrite_repository.dart';
import '../../pages/tank/tank_view.dart';
import '../graph/graph_view.dart';
import '../login/login_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() {}

  void getTankList() async {
    isloadingList(true);
    bool isErrorByLoading = false;
    String message = '';
    try {
      await _authRepository
          .listTankStops(szRxUserId.value)
          .then((tankListData) {
        if (tankListData.documents.isEmpty) {
          isErrorByLoading = true;
          message = 'Leere Liste keine Daten vorhanden';
          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();
        //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';
      }).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';
    Get.snackbar(
      title,
      message,
      backgroundColor: isErrorByLoading ? Colors.red : Colors.green,
      snackPosition: SnackPosition.BOTTOM,
      duration: const Duration(seconds: 4),
    );
    update();
  }

  void goToUpdatePage() {
    // Go to Update Page
  }
  void goToInputPage() {
    Get.offAndToNamed(TankPage.namedRoute);
  }

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