package com.example.lexilearn.ui.views.pResultScreening

import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import com.example.lexilearn.data.model.CompetitionScore
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.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.UUID

class ResultScreeningViewModel(application: Application) : AndroidViewModel(application) {
    private val database: DatabaseReference = FirebaseDatabase.getInstance().getReference("competitions")
    private val materialRepo = MaterialRepository(application)
    private val userRepository = UserRepository(application)

    private val _positionScore = MutableStateFlow(0)
    val positionScore: StateFlow<Int> = _positionScore

    private fun getTodayDate(): String {
        val dateFormat = SimpleDateFormat("dd-MM-yyyy", Locale.getDefault())
        return dateFormat.format(Date())
    }

    fun submitScore(score: Int) {

        userRepository.getUserData {dataUser->
            val todayDate = getTodayDate()
            val dateRef = database.child(todayDate)

            // Buat ID unik untuk skor
            val scoreId = dateRef.push().key ?: UUID.randomUUID().toString()
            val scoreData = mapOf("score" to score, "name" to "${dataUser?.name}")

            dateRef.child(scoreId).setValue(scoreData)
                .addOnSuccessListener {
                    Log.d("CompetitionViewModel", "Score added successfully!")
                    checkUserRanking(todayDate, scoreId, score)
                }
                .addOnFailureListener {
                    Log.e("CompetitionViewModel", "Error saving score: ${it.message}")
                }
        }
    }

    private fun checkUserRanking(todayDate: String, scoreId: String, userScore: Int) {
        val dateRef = database.child(todayDate)

        dateRef.orderByChild("score").addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {
                val scoreList = mutableListOf<Pair<String, Int>>() // (scoreId, score)

                for (scoreSnapshot in snapshot.children) {
                    val id = scoreSnapshot.key ?: continue
                    val score = scoreSnapshot.child("score").getValue(Int::class.java) ?: 0
                    scoreList.add(id to score)
                }

                // Urutkan skor dari tertinggi ke terendah
                val sortedScores = scoreList.sortedByDescending { it.second }

                // Cari posisi user
//                val userRank = sortedScores.indexOfFirst { it.first == scoreId } + 1
                val userRank = maxOf(1, sortedScores.indexOfFirst { it.first == scoreId } + 1)

                _positionScore.value = userRank

                if (userRank > 0) {
                    Log.d("ResultScreeningVM", "User is ranked: #$userRank out of ${sortedScores.size}")
                } else {
                    Log.d("ResultScreeningVM", "User rank not found.")
                }
            }

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

}