package com.example.lexilearn.data.remote


import android.content.Context
import android.util.Log
import com.example.lexilearn.data.model.MaterialDataModel
import com.example.lexilearn.data.local.SharedPrefHelper
import com.example.lexilearn.data.model.UserModel
import com.google.firebase.database.*
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase

class FirebaseHelper(private val context: Context) {
    private val sharedPrefHelper = SharedPrefHelper(context)

    // 🔥 Fungsi untuk mengambil data berdasarkan filterMaterial (kode lama, tetap dipertahankan)
    fun fetchMaterials(filterMaterial: String, callback: (List<MaterialDataModel>) -> Unit) {
        val databaseReference: DatabaseReference =
            FirebaseDatabase.getInstance().getReference("data/$filterMaterial")

        databaseReference.addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {
                val materialList = mutableListOf<MaterialDataModel>()
                for (materialSnapshot in snapshot.children) {
                    val material = materialSnapshot.getValue(MaterialDataModel::class.java)
                    material?.let { materialList.add(it) }
                }

                sharedPrefHelper.saveMaterialList(filterMaterial, materialList)
                callback(materialList)
            }

            override fun onCancelled(error: DatabaseError) {
                Log.e("FirebaseHelper", "Error: ${error.message}")
            }
        })
    }

    fun fetchAllMaterials(callback: (List<MaterialDataModel>) -> Unit) {
        val databaseReference: DatabaseReference = FirebaseDatabase.getInstance().getReference("data")

        databaseReference.addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {
                val allMaterials = mutableListOf<MaterialDataModel>()

                for (categorySnapshot in snapshot.children) { // Loop setiap kategori (animal, limb, dll.)
                    val categoryKey = categorySnapshot.key ?: continue
                    val materialList = mutableListOf<MaterialDataModel>()

                    for (materialSnapshot in categorySnapshot.children) { // Loop setiap item dalam kategori
                        val material = materialSnapshot.getValue(MaterialDataModel::class.java)
                        material?.let {
                            allMaterials.add(it)  // Tambahkan ke list utama
                            materialList.add(it)  // Tambahkan ke list per kategori
                        }
                    }

                    // Simpan berdasarkan kategori (misalnya "animal", "limb", dll.)
                    sharedPrefHelper.saveMaterialList(categoryKey, materialList)
                }

                // Simpan semua data ke SharedPreferences dengan key "all"
                sharedPrefHelper.saveMaterialList("all", allMaterials)

                // Callback dengan seluruh data sebagai satu List<MaterialDataModel>
                callback(allMaterials)
            }

            override fun onCancelled(error: DatabaseError) {
                Log.e("FirebaseHelper", "Error fetching all materials: ${error.message}")
                callback(emptyList()) // Jika terjadi error, kembalikan list kosong
            }
        })
    }


    // ✅ 🔥 Fungsi Login - Mencari user berdasarkan email dan password
    fun loginUser(email: String, password: String, callback: (Boolean, String?) -> Unit) {
        val databaseReference: DatabaseReference = FirebaseDatabase.getInstance().getReference("users")

        databaseReference.addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {
                for (userSnapshot in snapshot.children) {
                    val user = userSnapshot.getValue(UserModel::class.java)
                    if (user != null && user.email == email && user.password == password) {
                        val userId = userSnapshot.key // Ambil ID pengguna
                        sharedPrefHelper.saveUserId(userId!!) // Simpan ID ke SharedPreferences
                        callback(true, userId)
                        return
                    }
                }
                callback(false, null) // Jika tidak ditemukan
            }

            override fun onCancelled(error: DatabaseError) {
                Log.e("FirebaseHelper", "Error: ${error.message}")
                callback(false, null)
            }
        })
    }

    // ✅ 🔥 Fungsi Fetch User Data Berdasarkan ID (Dapatkan data user setelah login)
    fun fetchUserData(callback: (UserModel?) -> Unit) {
        val userId = sharedPrefHelper.getUserId()

        if (userId == null) {
            callback(null)
            return
        }

        val databaseReference: DatabaseReference = FirebaseDatabase.getInstance().getReference("users/$userId")

        databaseReference.addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {
                val user = snapshot.getValue(UserModel::class.java)
                callback(user)
            }

            override fun onCancelled(error: DatabaseError) {
                Log.e("FirebaseHelper", "Error: ${error.message}")
                callback(null)
            }
        })
    }
}
