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.UserDataModel
import com.google.firebase.database.*
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

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)
//            }
//        })
//    }
    fun loginUser(callback: (Boolean, String?) -> Unit) {
        val databaseReference: DatabaseReference =
            FirebaseDatabase.getInstance().getReference("users")
        val userId =
            sharedPrefHelper.getUserId() // Ambil ID pengguna yang disimpan di SharedPreferences

        if (userId.isNullOrEmpty()) {
            callback(false, null) // Jika tidak ada ID tersimpan
            return
        }

        databaseReference.child(userId).addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {
                if (snapshot.exists()) {
                    callback(true, userId)
                } else {
                    callback(false, null) // Jika user ID tidak ditemukan di database
                }
            }

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

    fun createUser(user: UserDataModel, callback: (Boolean, String?) -> Unit) {
        val databaseReference = FirebaseDatabase.getInstance().getReference("users")

        val userId = databaseReference.push().key

        if (userId != null) {
            databaseReference.child(userId).setValue(user).addOnCompleteListener { task ->
                if (task.isSuccessful) {
                    sharedPrefHelper.saveUserId(userId) // Simpan user ID
                    callback(true, userId)
                } else {
                    callback(false, null)
                }
            }
        } else {
            callback(false, null)
        }
    }

fun updateUser(updatedUser: UserDataModel, callback: (Boolean) -> Unit) {
val userId = sharedPrefHelper.getUserId()
val databaseReference = FirebaseDatabase.getInstance().getReference("users")
val newData = mapOf(
"name" to updatedUser.name,
"age" to updatedUser.age,
)
if (userId != null) {
databaseReference.child(userId).updateChildren(newData).addOnCompleteListener { task ->
callback(task.isSuccessful)
}
}
}

    // ✅ 🔥 Fungsi Fetch User Data Berdasarkan ID (Dapatkan data user setelah login)
    fun fetchUserData(callback: (UserDataModel?) -> 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(UserDataModel::class.java)
                callback(user)
            }

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

    fun fetchTop10Scores(callback: (List<Pair<String, Int>>) -> Unit) {
        val todayDate = getTodayDate()
        val databaseReference: DatabaseReference =
            FirebaseDatabase.getInstance().getReference("competitions/$todayDate")

        databaseReference.addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {
                val scoreList = mutableListOf<Pair<String, Int>>()

                for (scoreSnapshot in snapshot.children) {
                    val name = scoreSnapshot.child("name").getValue(String::class.java) ?: "Unknown"
                    val score = scoreSnapshot.child("score").getValue(Int::class.java) ?: 0
                    scoreList.add(Pair(name, score))
                }

                // Urutkan berdasarkan skor tertinggi dan ambil 10 data
                val top10Scores = scoreList.sortedByDescending { it.second }.take(10)
                callback(top10Scores)
            }

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

    fun getTodayDate(): String {
        val dateFormat = SimpleDateFormat("dd-MM-yyyy", Locale.getDefault())
        return dateFormat.format(Date()) // Mendapatkan tanggal hari ini (misalnya "25-02-2025")
    }
}
