import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:get_storage/get_storage.dart';
import 'package:nutriplant/app/routes/app_pages.dart';

class LoginController extends GetxController {
  var emailController = TextEditingController();
  var passwordController = TextEditingController();
  var isLoading = false.obs;

  final FirebaseAuth _auth = FirebaseAuth.instance;
  final GetStorage storage = GetStorage(); // Tambahkan GetStorage

  void login() async {
    String email = emailController.text.trim();
    String password = passwordController.text.trim();

    if (email.isEmpty || password.isEmpty) {
      showSnackbar("Error", "Email dan password tidak boleh kosong", Color(0xFFE88484));
      return;
    }

    try {
      isLoading.value = true;

      // **Melakukan autentikasi dengan Firebase**
      UserCredential userCredential = await _auth.signInWithEmailAndPassword(email: email, password: password);
      
      isLoading.value = false;
      showSnackbar("Success", "Login berhasil", Colors.green);

      // **Simpan status login di GetStorage**
      storage.write("isLoggedIn", true);
      storage.write("userEmail", userCredential.user?.email);

      // **Navigasi ke halaman utama**
      Get.offAllNamed(Routes.NAVBAR);
    } on FirebaseAuthException catch (e) {
      isLoading.value = false;

      String errorMessage;
      switch (e.code) {
        case 'invalid-email':
          errorMessage = "Format email tidak valid.";
          break;
        case 'user-not-found':
          errorMessage = "Akun tidak ditemukan. Periksa kembali email Anda.";
          break;
        case 'wrong-password':
          errorMessage = "Password salah. Coba lagi.";
          break;
        case 'too-many-requests':
          errorMessage = "Terlalu banyak percobaan. Coba lagi nanti.";
          break;
        default:
          errorMessage = "Terjadi kesalahan. Coba lagi nanti.";
      }

      showSnackbar("Login Gagal", errorMessage, Colors.redAccent);
    } catch (e) {
      isLoading.value = false;
      showSnackbar("Error", "Terjadi kesalahan: ${e.toString()}", Colors.redAccent);
    }
  }

  void showSnackbar(String title, String message, Color backgroundColor) {
    Get.snackbar(
      title,
      message,
      snackPosition: SnackPosition.BOTTOM,
      backgroundColor: backgroundColor,
      colorText: Colors.white,
    );
  }

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