package com.example.lexilearn.data.repository

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

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

    fun updateUser(updatedUser: UserDataModel, callback: (Boolean) -> Unit) {
        firebaseHelper.updateUser(updatedUser, callback)
    }

    fun createUser(user: UserDataModel, callback: (Boolean, String?) -> Unit) {
        firebaseHelper.createUser(user, callback)
    }

    fun loginUser(callback: (Boolean, String?) -> Unit) {
        firebaseHelper.loginUser { success, userId ->
            if (success && userId != null) {
                sharedPrefHelper.saveUserId(userId)
                callback(true, userId)
            } else {
                callback(false, null)
            }
        }
    }

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

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

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

        userRef.get().addOnSuccessListener { snapshot ->
            val currentValue = snapshot.getValue(Int::class.java) ?: 0
            if (value > currentValue) {
                userRef.setValue(value).addOnCompleteListener { task ->
                    if (task.isSuccessful) {
                        sharedPrefHelper.getUserData()?.let { updatedUser ->
                            updatedUser.unlock_data?.apply {
                                when (idUnlock) {
                                    "animal" -> animal = value
                                    "family" -> family = value
                                    "house" -> house = value
                                    "limb" -> limb = value
                                }
                            }
                            sharedPrefHelper.saveUserData(updatedUser)
                            println("printUpdateUnlock: successfully updated Firebase and SharedPreferences")
                            callback(true)
                        } ?: run {
                            println("printUpdateUnlock: updatedUser is null after updating Firebase")
                            callback(false)
                        }
                    } else {
                        println("printUpdateUnlock: task is not successful")
                        callback(false)
                    }
                }
            } else {
                println("printUpdateUnlock: new value $value is not greater than current value $currentValue")
                callback(false)
            }
        }.addOnFailureListener {
            println("printUpdateUnlock: failed to get data: ${it.message}")
            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")
        userRef.get().addOnSuccessListener { snapshot ->
            callback(snapshot.getValue(Int::class.java) ?: 0)
        }.addOnFailureListener {
            callback(null)
        }
    }

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