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

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

  final RxBool isLoading = false.obs;
  final RxBool showPassword = false.obs;
  final RxBool isChecked = false.obs;
  final RxBool showSplash = 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;

    showSplash.value = true; 

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

      final errors = await AuthService.loginUser(loginData);

      if (errors != null) {
        showAppSnackbar(
          title: "Login Failed",
          message: "Username or password is incorrect",
          type: SnackbarType.error,
        );
        basicValidator.addErrors(errors);
        basicValidator.validateForm();
        basicValidator.clearErrors();
      } else {
        await _handleRememberMe();
        enableRemoteLogging();
        logSafe("Login successful for user: ${loginData['username']}");
        Get.offNamed('/select-tenant'); 
      }
    } catch (e, stacktrace) {
      showAppSnackbar(
        title: "Login Error",
        message: "An unexpected error occurred",
        type: SnackbarType.error,
      );
      logSafe("Exception during login",
          level: LogLevel.error, error: e, stackTrace: stacktrace);
    } finally {
      showSplash.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');
}
