import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class ChangePasswordController extends GetxController {
  var isLoading = false.obs;

  Future<void> changePassword({
  required String currentPassword,
  required String newPassword,
}) async {
  try {
    isLoading.value = true;

    final user = FirebaseAuth.instance.currentUser!;

    final cred = EmailAuthProvider.credential(
      email: user.email!,
      password: currentPassword,
    );

    // ✅ Re-authenticate
    await user.reauthenticateWithCredential(cred);

    // ✅ Update Password
    await user.updatePassword(newPassword);

    Get.snackbar(
      "Berhasil",
      "Kata sandi berhasil diperbarui",
      snackPosition: SnackPosition.TOP,
      backgroundColor: Colors.white,
      colorText: Colors.black,
      margin: const EdgeInsets.all(12),
      borderRadius: 12,
      icon: const Icon(Icons.check_circle, color: Colors.green),
    );
  } on FirebaseAuthException catch (e) {
    String message = "Terjadi kesalahan";

    // ✅ HANDLE ERROR FIREBASE
    switch (e.code) {
      case 'wrong-password':
      case 'invalid-credential':
        message = "Password lama tidak sesuai";
        break;

      case 'weak-password':
        message = "Password terlalu lemah (minimal 6 karakter)";
        break;

      case 'requires-recent-login':
        message = "Silakan login ulang terlebih dahulu";
        break;

      default:
        message = e.message ?? "Gagal memperbarui kata sandi";
    }

    Get.snackbar(
      "Error",
      message,
      snackPosition: SnackPosition.TOP,
      backgroundColor: Colors.white,
      colorText: Colors.black,
      margin: const EdgeInsets.all(12),
      borderRadius: 12,
      icon: const Icon(Icons.error, color: Colors.red),
    );
  } finally {
    isLoading.value = false;
  }
}

}