package com.example.lexilearn.ui.views.pHome

import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.example.lexilearn.data.model.CompetitionScore
import com.example.lexilearn.data.model.MaterialDataModel
import com.example.lexilearn.data.model.UserDataModel
import com.example.lexilearn.data.repository.MaterialRepository
import com.example.lexilearn.data.repository.QuizRepository
import com.example.lexilearn.data.repository.UserRepository
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class HomeViewModel(application: Application) : AndroidViewModel(application) {

    private val totalDataCompetition = 5

    val materialRepository = MaterialRepository(application)
    val userRepository = UserRepository(application)
    private val _quizRepository = QuizRepository()

    private val _dialogProfile = MutableStateFlow<Boolean>(false)
    val dialogProfile: StateFlow<Boolean> get() = _dialogProfile.asStateFlow()

    private val database: DatabaseReference =
        FirebaseDatabase.getInstance().getReference("competitions")

    private val _topScores = MutableStateFlow<List<CompetitionScore>>(emptyList())
    val topScores: StateFlow<List<CompetitionScore>> get() = _topScores.asStateFlow()

    val _userData = MutableStateFlow<UserDataModel?>(null)
    val userData = _userData.asStateFlow()

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

    init {
        fetchTop10Scores()
        getUserData()
    }


    fun getUserData() {
        viewModelScope.launch {
            delay(3000)
            userRepository.getUserData { data ->
                _userData.value = data
            }
        }
    }


    // 🔥 Fungsi untuk mengambil 10 skor tertinggi secara real-time dari Firebase
    private fun fetchTop10Scores() {
        val todayDate = getTodayDate()
        val dateRef = database.child(todayDate)

        dateRef.orderByChild("score").limitToLast(10)
            .addValueEventListener(object : ValueEventListener {
                override fun onDataChange(snapshot: DataSnapshot) {
                    val scoreList = mutableListOf<CompetitionScore>()
                    for (scoreSnapshot in snapshot.children) {
                        val scoreData = scoreSnapshot.getValue(CompetitionScore::class.java)
                        scoreData?.let { scoreList.add(it) }
                    }
                    _topScores.value = scoreList.sortedByDescending { it.score }
                }

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

    fun prepareCompetitionQuiz(callback: (List<MaterialDataModel>) -> Unit) {
        materialRepository.getAllMaterialData("all") { materials ->
            _quizRepository.getRandomMaterials(totalDataCompetition, materials) { randomData ->
                randomData.forEach { println(it) }
                callback(randomData)
            }
        }
    }

    fun showHiddenDialog() {
        _dialogProfile.value = !_dialogProfile.value
    }
}