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/app_logger.dart';

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

  @override
  void onInit() {
    super.onInit();
    logSafe("[ResetPasswordController] onInit called");

    basicValidator.addField(
      'password',
      required: true,
      validators: [MyLengthValidator(min: 6, max: 10)],
      controller: TextEditingController(),
    );

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

  Future<void> onResetPassword() async {
    logSafe("[ResetPasswordController] onResetPassword triggered");

    if (basicValidator.validateForm()) {
      final data = basicValidator.getData();
      logSafe("[ResetPasswordController] Reset password form data");

      update();

      final errors = await AuthService.loginUser(data); // Consider renaming this to resetPassword() for clarity
      if (errors != null) {
        logSafe("[ResetPasswordController] Received errors: $errors", level: LogLevel.warning);
        basicValidator.addErrors(errors);
        basicValidator.validateForm();
        basicValidator.clearErrors();
      }

      logSafe("[ResetPasswordController] Navigating to /dashboard");
      Get.toNamed('/dashboard');
      update();
    } else {
      logSafe("[ResetPasswordController] Form validation failed", level: LogLevel.warning);
    }
  }

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

  void onConfirmPassword() {
    confirmPassword = !confirmPassword;
    logSafe("[ResetPasswordController] confirmPassword toggled: $confirmPassword");
    update();
  }
}
