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/widgets/my_snackbar.dart';
import 'package:on_field_work/helpers/services/app_logger.dart'; 
import 'package:on_field_work/helpers/services/storage/local_storage.dart';

class ForgotPasswordController extends MyController {
  final MyFormValidator basicValidator = MyFormValidator();
  final RxBool isLoading = false.obs;

  @override
  void onInit() {
    super.onInit();
    basicValidator.addField(
      'email',
      required: true,
      label: "Email",
      validators: [MyEmailValidator()],
      controller: TextEditingController(text: "demo@example.com"),
    );
  }

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

    isLoading.value = true;
    final data = basicValidator.getData();
    final email = data['email']?.toString() ?? '';

    try {
      logSafe("Forgot password requested for: $email",  );

      final result = await AuthService.forgotPassword(email);

      if (result == null) {
        showAppSnackbar(
          title: "Success",
          message: "Password reset link has been sent.",
          type: SnackbarType.success,
        );
        await LocalStorage.logout();
      } else {
        final errorMessage = result['error'] ?? "Failed to send reset link. Please try again.";
        showAppSnackbar(
          title: "Failed",
          message: errorMessage,
          type: SnackbarType.error,
        );
        logSafe("Failed to send reset password email for $email: $errorMessage", level: LogLevel.warning,  );
      }
    } catch (e, stacktrace) {
      logSafe("Error during forgot password", level: LogLevel.error, error: e, stackTrace: stacktrace);
      showAppSnackbar(
        title: "Error",
        message: "Something went wrong. Please try again later.",
        type: SnackbarType.error,
      );
    } finally {
      isLoading.value = false;
    }
  }

  void gotoLogIn() {
    Get.offAllNamed('/auth/login-option');
  }
}
