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

import '../../data/repository/appwrite_repository.dart';
import '../../utils/extensions/static_helper.dart';
import '../tank/tank_view.dart';

class LoginController extends GetxController {
  final AppwriteRepository _authRepository = AppwriteRepository();

  final isVisible = false.obs;
  //Form Key
  final formKey = GlobalKey<FormState>();
  bool isFormValid = false;

  final _dataBox = GetStorage('MyUserStorage');

  final emailController = TextEditingController();
  final passwordController = TextEditingController();
  final nameController = TextEditingController();

  @override
  void onInit() {
    super.onInit();
    print('LoginController initialized');
  }

  @override
  void onReady() {
    super.onReady();
    // Initialize any necessary data or state here
    var isSessionId = _dataBox.hasData('sessionId');
    if (isSessionId) {
      // If session ID exists, navigate to TankPage
      print('Session ID found, navigating to TankPage');
      goToTankPage();
    } else {
      // If no session ID, initialize the login controller
      print('No session ID found, initializing LoginController');
    }
    // This method is called when the controller is ready
    print('LoginController is ready');
  }

  @override
  void onClose() {
    // Clean up any resources or listeners here
    emailController.dispose();
    passwordController.dispose();
    nameController.dispose();
    // emailFocusNode.dispose();
    // passwordFocusNode.dispose();
    // nameFocusNode.dispose();
    super.onClose();
  }

  void clearTextEditingController() {
    emailController.clear();
    passwordController.clear();
    nameController.clear();
  }

  String? validateEmail(String? value) {
    if (value == null || value.isEmpty) {
      return 'Bitte geben Sie eine E-Mail-Adresse ein';
    }
    if (!GetUtils.isEmail(value)) {
      return 'Bitte geben Sie eine gültige E-Mail-Adresse ein';
    }
    return null;
  }

  String? validatePassword(String? value) {
    if (value == null || value.isEmpty) {
      return 'Bitte geben Sie ein Passwort ein';
    }
    if (value.length < 8) {
      return 'Das Passwort muss mindestens 8 Zeichen lang sein';
    }
    return null;
  }

  String? validateName(String? value) {
    if (value == null || value.isEmpty) {
      return 'Bitte geben Sie Ihren Namen ein';
    }
    if (value.length < 3) {
      return 'Der Name muss mindestens 3 Zeichen lang sein';
    }
    return null;
  }

  var message = 'NoMessage!';
  var isError = false;

  // Registrierung
  Future<void> register() async {
    isError = false;
    message = 'NoMessage!';
    isFormValid = formKey.currentState!.validate();
    if (!isFormValid) {
      print('Formular ist ungültig');
      return;
    } else {
      print('Formular ist gültig');
      formKey.currentState!.save();
      try {
        await _authRepository.signup({
          'email': emailController.text,
          'password': passwordController.text,
          'name': nameController.text,
        }).then((models.User userValue) {
          // GetStorage data storage
          isVisible(false);
          print(
            'User was stored and Loggedin: ${userValue.name}, ${userValue.$id}, ${userValue.email}',
          );
          // Store session ID in GetStorage
          _dataBox.write('userId', userValue.$id);
          _dataBox.write('userName', userValue.name);
          _dataBox.write('userEmail', userValue.email);
          // Go to TankPage
          goToTankPage();
          message = 'Sie wurden registriert und Angemeldet!!';
          StaticHelper.getMySnackeBar('Erfolg', message, Colors.green);
        }).catchError((error) {
          if (error is AppwriteException) {
            // Handle specific Appwrite exceptions
            print('Appwrite Fehler: ${error.message}');
            message = 'Appwrite Fehler: ${error.message}';
            isError = true;
          } else {
            // Handle other types of errors
            message = 'Allgemeiner Fehler: $error';
            print('Allgemeiner Fehler: $error');
            isError = true;
          }
          message = 'Fehler bei der Registrierung: $error';
          print('Fehler bei der Registrierung: $error');
          //Clear GetStorage session ID
          StaticHelper.removeFromStorage();
          isError = true;
        });
      } catch (e) {
        message = 'Fehler bei Registrierung: $e';
        print('Fehler bei Registrierung: $e');
        //Clear GetStorage session ID
        StaticHelper.removeFromStorage();
        isError = true;
      }
      if (isError) StaticHelper.getMySnackeBar('Fehler', message, Colors.red);
    }
  }

  Future<void> _getCurrentLoggedinUser() async {
    await _authRepository.getCurrentUser.then((models.User userValue) {
      // GetStorage data storage
      print(
        'User was stored and Loggedin: ${userValue.name}, ${userValue.$id}, ${userValue.email}',
      );
      // Store session ID in GetStorage
      _dataBox.write('userId', userValue.$id);
      _dataBox.write('userName', userValue.name);
      _dataBox.write('userEmail', userValue.email);
    }).catchError((error) {
      print('Fehler beim Abrufen des Benutzers: $error');
    });
  }

  // Login
  Future<void> login() async {
    message = 'NoMessage!';
    isError = false;

    isFormValid = formKey.currentState!.validate();
    if (!isFormValid) {
      print('Formular ist ungültig');
      return;
    } else {
      print('Formular ist gültig');
      formKey.currentState!.save();
      try {
        await _authRepository.login({
          'email': emailController.text,
          'password': passwordController.text,
        }).then((models.Session session) {
          // Store session ID in GetStorage
          _dataBox.write('sessionId', session.$id);
          print('Session ID stored: ${_dataBox.read('sessionId')}');
          print(
            'Erfolgreich eingeloggt: ${session.$id}\n${session.providerUid}',
          );
          _getCurrentLoggedinUser().then((_) {
            // Go to TankPage
            goToTankPage();
            StaticHelper.getMySnackeBar(
                'Erfolg', 'Sie wurden Angemeldet!!', Colors.green);
          });
        }).catchError((error) {
          if (error is AppwriteException) {
            // Handle specific Appwrite exceptions
            isError = true;
            message = 'Appwrite Fehler: ${error.message}';
            print('Appwrite Fehler: ${error.message}');
          } else {
            // Handle other types of errors
            print('Allgemeiner Fehler: $error');
            isError = true;
            message = 'Allgemeiner Fehler: $error';
          }
          print('Fehler beim Login: $error');
          isError = true;
          message = 'Fehler beim Login: $error';
          _authRepository.logout();
        });
      } catch (e) {
        print('Fehler beim Login: $e');
        isError = true;
        message = 'Fehler beim Login: $e';
        _authRepository.logout();
      }
      if (isError) StaticHelper.getMySnackeBar('Fehler', message, Colors.red);
    }
  }

  void goToTankPage() {
    Get.offAndToNamed(TankPage.namedRoute);
  }
}
