import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:marco/controller/my_controller.dart';
import 'package:marco/helpers/services/auth_service.dart';
import 'package:marco/helpers/widgets/my_form_validator.dart';
import 'package:marco/helpers/widgets/my_validators.dart';
import 'package:marco/helpers/services/storage/local_storage.dart';
import 'package:marco/helpers/widgets/my_snackbar.dart';
import 'package:marco/helpers/services/app_logger.dart'; // <-- logging

class LoginController extends MyController {
  final MyFormValidator basicValidator = MyFormValidator();

  final RxBool isLoading = false.obs;
  final RxBool showPassword = false.obs;
  final RxBool isChecked = false.obs;

  @override
  void onInit() {
    super.onInit();
    _initializeForm();
    _loadSavedCredentials();
  }

  void _initializeForm() {
    basicValidator.addField(
      'username',
      required: true,
      label: "User_Name",
      validators: [MyEmailValidator()],
      controller: TextEditingController(),
    );

    basicValidator.addField(
      'password',
      required: true,
      label: "Password",
      validators: [MyLengthValidator(min: 6)],
      controller: TextEditingController(),
    );
  }

  void onChangeCheckBox(bool? value) {
    isChecked.value = value ?? false;
  }

  void onChangeShowPassword() {
    showPassword.toggle();
  }

  Future<void> onLogin() async {
    if (!basicValidator.validateForm()) return;

    isLoading.value = true;

    try {
      final loginData = basicValidator.getData();
      logSafe("Attempting login for user: ${loginData['username']}",  );

      final errors = await AuthService.loginUser(loginData);

      if (errors != null) {
        logSafe("Login failed for user: ${loginData['username']} with errors: $errors", level: LogLevel.warning,  );

        showAppSnackbar(
          title: "Login Failed",
          message: "Username or password is incorrect",
          type: SnackbarType.error,
        );

        basicValidator.addErrors(errors);
        basicValidator.validateForm();
        basicValidator.clearErrors();
      } else {
        await _handleRememberMe();
        logSafe("Login successful for user: ${loginData['username']}",  );
        Get.toNamed('/home');
      }
    } catch (e, stacktrace) {
      logSafe("Exception during login", level: LogLevel.error, error: e, stackTrace: stacktrace);
      showAppSnackbar(
        title: "Login Error",
        message: "An unexpected error occurred",
        type: SnackbarType.error,
      );
    } finally {
      isLoading.value = false;
    }
  }

  Future<void> _handleRememberMe() async {
    if (isChecked.value) {
      await LocalStorage.setToken('username', basicValidator.getController('username')!.text);
      await LocalStorage.setToken('password', basicValidator.getController('password')!.text);
      await LocalStorage.setBool('remember_me', true);
    } else {
      await LocalStorage.removeToken('username');
      await LocalStorage.removeToken('password');
      await LocalStorage.setBool('remember_me', false);
      basicValidator.clearErrors();
    }
  }

  Future<void> _loadSavedCredentials() async {
    final savedUsername = LocalStorage.getToken('username');
    final savedPassword = LocalStorage.getToken('password');
    final remember = LocalStorage.getBool('remember_me') ?? false;

    isChecked.value = remember;

    if (remember) {
      basicValidator.getController('username')?.text = savedUsername ?? '';
      basicValidator.getController('password')?.text = savedPassword ?? '';
    }
  }

  void goToForgotPassword() {
    Get.toNamed('/auth/forgot_password');
  }

  void gotoRegister() {
    Get.offAndToNamed('/auth/register_account');
  }
}
