import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sigap/src/features/auth/data/repositories/authentication_repository.dart';
import 'package:sigap/src/shared/widgets/state_screeen/state_screen.dart';
import 'package:sigap/src/utils/constants/image_strings.dart';
import 'package:sigap/src/utils/popups/loaders.dart';
import 'package:sigap/src/utils/validators/validation.dart';

class ForgotPasswordController extends GetxController {
  // Singleton instance
  static ForgotPasswordController get instance => Get.find();

  // Form key for validation
  final formKey = GlobalKey<FormState>();

  // Text controllers
  final emailController = TextEditingController();

  // Observable variables
  final RxBool isLoading = false.obs;
  final RxString emailError = ''.obs;
  final RxBool isEmailSent = false.obs;

  @override
  void onClose() {
    emailController.dispose();
    super.onClose();
  }

  // Validate email
  String? validateEmail(String? value) {
    final error = TValidators.validateEmail(value);
    emailError.value = error ?? '';
    return error;
  }

  // Reset password method
  Future<void> resetPassword() async {
    // Clear previous errors
    emailError.value = '';

    // Validate form
    if (formKey.currentState?.validate() != true) {
      return;
    }

    try {
      isLoading.value = true;

      await AuthenticationRepository.instance.sendResetPasswordForEmail(
        emailController.text,
      );

      // Show success message
      isEmailSent.value = true;
      TLoaders.successSnackBar(
        title: 'Success',
        message: 'Reset password email sent successfully.',
      );

      Get.off(
        () => StateScreen(
          title: 'Check Your Email',
          subtitle: 'Please check your email for the reset link.',
          image: TImages.customerSupport,
          isSvg: true,
          primaryButtonTitle: 'Go Back',
          showButton: true,

          onPressed: () => Get.back(),
        ),
      );
    } catch (e) {
      Get.snackbar(
        'Error',
        'Failed to send reset email: ${e.toString()}',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
    } finally {
      isLoading.value = false;
    }
  }

  // Go back to sign in
  void goBack() {
    Get.back();
  }
}
