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/widgets/my_form_validator.dart';
import 'package:on_field_work/helpers/widgets/my_validators.dart';
import 'package:on_field_work/helpers/services/auth_service.dart';
import 'package:on_field_work/helpers/services/app_logger.dart';

class RegisterAccountController extends MyController {
  MyFormValidator basicValidator = MyFormValidator();
  bool showPassword = false;

  @override
  void onInit() {
    logSafe("[RegisterAccountController] onInit called");

    basicValidator.addField(
      'email',
      required: true,
      label: "Email",
      validators: [MyEmailValidator()],
      controller: TextEditingController(),
    );
    basicValidator.addField(
      'first_name',
      required: true,
      label: 'First Name',
      controller: TextEditingController(),
    );
    basicValidator.addField(
      'last_name',
      required: true,
      label: 'Last Name',
      controller: TextEditingController(),
    );
    basicValidator.addField(
      'password',
      required: true,
      validators: [MyLengthValidator(min: 6, max: 10)],
      controller: TextEditingController(),
    );

    super.onInit();
  }

  Future<void> onLogin() async {
    if (basicValidator.validateForm()) {
      update();
      final data = basicValidator.getData();
      logSafe("[RegisterAccountController] Submitting registration data");

      final errors = await AuthService.loginUser(data);
      if (errors != null) {
        logSafe("[RegisterAccountController] Login errors: $errors", level: LogLevel.warning);
        basicValidator.addErrors(errors);
        basicValidator.validateForm();
        basicValidator.clearErrors();
      }

      logSafe("[RegisterAccountController] Redirecting to /starter");
      Get.toNamed('/starter');
      update();
    } else {
      logSafe("[RegisterAccountController] Validation failed", level: LogLevel.warning);
    }
  }

  void onChangeShowPassword() {
    showPassword = !showPassword;
    logSafe("[RegisterAccountController] showPassword toggled: $showPassword");
    update();
  }

  void gotoLogin() {
    logSafe("[RegisterAccountController] Navigating to /auth/login-option");
    Get.toNamed('/auth/login-option');
  }
}
