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 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) {
        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
        userRef.get().addOnSuccessListener { snapshot ->
            val currentValue = snapshot.getValue(Int::class.java) ?: 0

            // 🔥 Hanya update jika nilai baru lebih besar
            if (value > currentValue) {
                userRef.setValue(value).addOnCompleteListener { task ->
                    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
                            }
                        }
                        sharedPrefHelper.saveUserData(updatedUser!!)
                        callback(true)
                    } else {
                        callback(false)
                    }
                }
            } else {
                callback(false) // 🔥 Jika nilai baru <= nilai lama, tidak update
            }
        }.addOnFailureListener {
            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()
    }
}
