package com.example.lexilearn.data.repository

import android.content.Context
import com.example.lexilearn.data.local.SharedPrefHelper
import com.example.lexilearn.data.remote.FirebaseHelper
import com.example.lexilearn.data.model.MaterialDataModel
import com.example.lexilearn.data.model.UserModel
import com.google.firebase.database.FirebaseDatabase

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

    fun getMaterialData(filterMaterial: String, callback: (List<MaterialDataModel>) -> Unit) {
        val cachedData =
            sharedPrefHelper.getMaterialList(filterMaterial)  // Ambil data dengan filter
        if (cachedData != null) {
            callback(cachedData)
        } else {
            firebaseHelper.fetchMaterials(filterMaterial) { materials ->
                sharedPrefHelper.saveMaterialList(
                    filterMaterial,
                    materials
                )
                callback(materials)
            }
        }
    }

    fun getAllMaterialData(filterMaterial: String, callback: (List<MaterialDataModel>) -> Unit) {
        val cachedData =
            sharedPrefHelper.getMaterialList(filterMaterial)  // Ambil data dengan filter
        if (cachedData != null) {
            callback(cachedData)
        } else {
            firebaseHelper.fetchAllMaterials { materials ->
                sharedPrefHelper.saveMaterialList(
                    filterMaterial,
                    materials
                )
                callback(materials)
            }
        }
    }

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

        // Buat user baru dengan ID unik
        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 loginUser(email: String, password: String, callback: (Boolean, String?) -> Unit) {
        firebaseHelper.loginUser(email, password) { success, userId ->
            if (success && userId != null) {
                sharedPrefHelper.saveUserId(userId)  // Simpan ID user
                callback(true, userId)
            } else {
                callback(false, null)
            }
        }
    }

    fun getUserData(callback: (UserModel?) -> Unit) {
        firebaseHelper.fetchUserData { user ->
            callback(user)
        }
    }

    fun updateUnlockData(idUnlock: String, value: Int, callback: (Boolean) -> Unit) {
        try {
            val userId = sharedPrefHelper.getUserId()
            if (userId == null) {
                println("printUpdateUnlock: userId is null")
                callback(false)
                return
            }

            val userRef = FirebaseDatabase.getInstance().getReference("users/$userId/unlock_data/$idUnlock")

            // Ambil data user dari Firebase dengan try-catch di dalam callback
            userRef.get().addOnSuccessListener { snapshot ->
                try {
                    val currentValue = snapshot.getValue(Int::class.java) ?: 0

                    // Hanya update jika nilai baru lebih besar
                    if (value > currentValue) {
                        userRef.setValue(value).addOnCompleteListener { task ->
                            try {
                                if (task.isSuccessful) {
                                    // Update juga di SharedPreferences
                                    val updatedUser = sharedPrefHelper.getUserData()
                                    updatedUser?.unlock_data?.let { unlockData ->
                                        when (idUnlock) {
                                            "animal" -> unlockData.animal = value
                                            "family" -> unlockData.family = value
                                            "house" -> unlockData.house = value
                                            "limb" -> unlockData.limb = value
                                        }
                                    }
                                    // Pastikan updatedUser tidak null sebelum menyimpan
                                    if (updatedUser != null) {
                                        println("printUpdateUnlock: successfully updated Firebase and SharedPreferences")
                                        sharedPrefHelper.saveUserData(updatedUser)
                                        callback(true)
                                    } else {
                                        println("printUpdateUnlock: updatedUser is null after updating Firebase")
                                        callback(false)
                                    }
                                } else {
                                    println("printUpdateUnlock: task is not successful")
                                    callback(false)
                                }
                            } catch (e: Exception) {
                                e.printStackTrace()
                                println("printUpdateUnlock: exception in onCompleteListener: $e")
                                callback(false)
                            }
                        }
                    } else {
                        println("printUpdateUnlock: new value $value is not greater than current value $currentValue")
                        callback(false) // Jika nilai baru <= nilai lama, tidak update
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    println("printUpdateUnlock: exception in onSuccessListener: $e")
                    callback(false)
                }
            }.addOnFailureListener {
                it.printStackTrace()
                println("printUpdateUnlock: failed to get data: ${it.message}")
                callback(false)
            }
        } catch (e: Exception) {
            println("printUpdateUnlock: error_update_unlock_data: $e")
            e.printStackTrace()
            callback(false)
        }
    }

//    fun updateUnlockData(idUnlock: String, value: Int, callback: (Boolean) -> Unit) {
//        try {
//            val userId = sharedPrefHelper.getUserId()
//            if (userId == null) {
//                callback(false)
//                return
//            }
//
//            val userRef = FirebaseDatabase.getInstance().getReference("users/$userId/unlock_data/$idUnlock")
//
//            // Ambil data user dari Firebase dengan try-catch di dalam callback
//            userRef.get().addOnSuccessListener { snapshot ->
//                try {
//                    val currentValue = snapshot.getValue(Int::class.java) ?: 0
//
//                    // Hanya update jika nilai baru lebih besar
//                    if (value > currentValue) {
//                        userRef.setValue(value).addOnCompleteListener { task ->
//                            try {
//                                if (task.isSuccessful) {
//                                    // Update juga di SharedPreferences
//                                    val updatedUser = sharedPrefHelper.getUserData()
//                                    updatedUser?.unlock_data?.let { unlockData ->
//                                        when (idUnlock) {
//                                            "animal" -> unlockData.animal = value
//                                            "family" -> unlockData.family = value
//                                            "house" -> unlockData.house = value
//                                            "limb" -> unlockData.limb = value
//                                        }
//                                    }
//                                    // Pastikan updatedUser tidak null sebelum menyimpan
//                                    if (updatedUser != null) {
//                                        sharedPrefHelper.saveUserData(updatedUser)
//                                        callback(true)
//                                    } else {
//                                        callback(false)
//                                    }
//                                } else {
//                                    callback(false)
//                                }
//                            } catch (e: Exception) {
//                                e.printStackTrace()
//                                callback(false)
//                            }
//                        }
//                    } else {
//                        callback(false) // Jika nilai baru <= nilai lama, tidak update
//                    }
//                } catch (e: Exception) {
//                    e.printStackTrace()
//                    callback(false)
//                }
//            }.addOnFailureListener {
//                it.printStackTrace()
//                callback(false)
//            }
//        } catch (e: Exception) {
//            println("error_update_unlock_data: $e")
//            e.printStackTrace()
//            callback(false)
//        }
//    }


    fun getUnlockValue(idUnlock: String, callback: (Int?) -> Unit) {
        val userId = sharedPrefHelper.getUserId()

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

        val userRef = FirebaseDatabase.getInstance().getReference("users/$userId/unlock_data/$idUnlock")

        // 🔥 Ambil nilai dari Firebase
        userRef.get().addOnSuccessListener { snapshot ->
            val currentValue = snapshot.getValue(Int::class.java) ?: 0
            callback(currentValue)
        }.addOnFailureListener {
            callback(null) // 🔥 Gagal mengambil data
        }
    }


    fun logoutUser() {
        sharedPrefHelper.clearUserData()
    }
}
