import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:maxdash/helpers/services/auth_service.dart';
import 'package:maxdash/helpers/widgets/my_form_validator.dart';

class LoginController extends GetxController {
  MyFormValidator basicValidator = MyFormValidator();

  bool showPassword = false;

  @override
  void onInit() {
    basicValidator.addField('username', required: true, label: "Username", controller: TextEditingController());
    basicValidator.addField('password', required: true, label: "Password", controller: TextEditingController());
    super.onInit();
  }

  void onChangeShowPassword() {
    showPassword = !showPassword;
    update();
  }
  void goToForgotPassword() {
    Get.toNamed('/auth/forgot_password');
  }

  void gotoRegister() {
    Get.offAndToNamed('/auth/register_account');
  }
Future<void> onLogin() async {
  if (basicValidator.validateForm()) {
    final data = basicValidator.getData();

    // Log the data being sent
    print('Sending login request with data: $data');

    // Show a loading dialog
    Get.dialog(
      Center(child: CircularProgressIndicator()),
      barrierDismissible: false,
    );

    try {
      // Call the AuthService to perform the login
      final errors = await AuthService.loginUser(data);
      print('Login errors: $errors');

      // Close the loading dialog
      Get.back();

      if (errors != null) {
        // Display errors if login fails
        print('Login failed with errors: $errors');
        basicValidator.addErrors(errors);
        basicValidator.validateForm();
        basicValidator.clearErrors();
      } else {
        // Navigate to the home screen on successful login
        print('Login successful. Navigating to home...');
        Get.offAllNamed('/home');
      }
    } catch (e) {
      // Close the loading dialog in case of an exception
      Get.back();

      // Show a generic error message
      print('Unexpected error: $e');
      Get.snackbar('Error', 'An unexpected error occurred. Please try again.');
    }
  }

}
}