package com.example.lexilearn.ui.views.pQuiz

import android.app.Application
import android.speech.tts.TextToSpeech
import android.util.Log
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.lexilearn.data.model.MaterialDataModel
import com.example.lexilearn.data.model.QuizQuestion
import com.example.lexilearn.data.repository.QuizRepository
import com.example.lexilearn.domain.models.ModelAnswerRead
import com.example.lexilearn.domain.models.ModelSpell
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import java.util.Locale

class QuizViewModel(application: Application) : AndroidViewModel(application),
    TextToSpeech.OnInitListener {
    private val quizRepository = QuizRepository()

    private val _currentQuestion = MutableStateFlow<QuizQuestion?>(null)
    val currentQuestion: StateFlow<QuizQuestion?> = _currentQuestion

    private val _userAnswer = MutableStateFlow<String?>(null)
    val userAnswer: StateFlow<String?> = _userAnswer

    private val _isAnswerCorrect = MutableStateFlow<Boolean?>(null)
    val isAnswerCorrect: StateFlow<Boolean?> = _isAnswerCorrect

    fun loadNewQuestion(material: MaterialDataModel, questionMode: Int, answerMode: Int) {
        _currentQuestion.value = quizRepository.generateQuestion(material, questionMode, answerMode)
    }

    private val _shuffledAnswerLetters = MutableStateFlow<List<ModelAnswerRead>>(emptyList())
    val shuffledAnswerLetters: StateFlow<List<ModelAnswerRead>> = _shuffledAnswerLetters


    private val _questionShuffled = MutableStateFlow<List<ModelSpell>>(emptyList())
    val questionShuffled: StateFlow<List<ModelSpell>> = _questionShuffled

    private val _isButtonVisible = mutableStateOf(false)
    val isButtonVisible: State<Boolean> get() = _isButtonVisible

    fun updateQuestionShuffled(index: Int, newData: ModelSpell) {
        _questionShuffled.value = _questionShuffled.value.mapIndexed { i, item ->
            if (i == index) {
                item.copy(
                    data = newData.data,
                    showCard = true,
                    emp = newData.emp,
                    hasContent = true
                )
            } else {
                item
            }
        }
    }


    fun loadRandomQuestion(material: MaterialDataModel) {
        _currentQuestion.value = quizRepository.generateQuestion(material, 2, 2)

        val dataQuest =
            _currentQuestion.value?.correctAnswer?.correctWord?.mapIndexed { index, char ->
                ModelSpell(index + 1, true, "?", showCard = false)
            } ?: emptyList()
        _questionShuffled.value = dataQuest

        val listAnswer =
            _currentQuestion.value?.correctAnswer?.correctWord?.mapIndexed { index, char ->
                ModelAnswerRead(index + 1, char.toString())
            } ?: emptyList()
        val shuflledAnswer = listAnswer.shuffled()
        _shuffledAnswerLetters.value = shuflledAnswer

        // Menambahkan delay 1 detik sebelum memanggil observeData()
//        viewModelScope.launch {
//            delay(1000L) // delay 1 detik
//
//        }
    }


    fun submitAnswer(answer: String) {
        _userAnswer.value = answer
        _isAnswerCorrect.value =
            _currentQuestion.value?.correctAnswer?.correctWord?.equals(answer, ignoreCase = true)
    }

    private var tts: TextToSpeech? = null
    private val _isTTSInitialized = MutableLiveData(false)
    val isTTSInitialized: LiveData<Boolean> = _isTTSInitialized

    init {
        tts = TextToSpeech(application, this)
        observeData()
    }

    override fun onInit(status: Int) {
        if (status == TextToSpeech.SUCCESS) {
            tts?.language = Locale.ENGLISH
            _isTTSInitialized.value = true
        } else {
            _isTTSInitialized.value = false
        }
    }

    fun speakLetter(letter: String) {
        if (_isTTSInitialized.value == true) {
            tts?.speak(letter, TextToSpeech.QUEUE_FLUSH, null, null)
        }
    }

    fun checkAnswer(answerString: String): Boolean {
        if (answerString == currentQuestion.value?.correctAnswer?.correctWord) {
            return true
        }
        return false
    }

    fun observeData() {
        viewModelScope.launch {
            _questionShuffled.collect { newList ->
                // Lakukan aksi setiap kali data berubah
                var answerString = ""
                newList.forEach { text ->
                    answerString = answerString + text.data
                }
                if (answerString.contains("?") || answerString.isEmpty() || answerString.contains("null")) {
                    _isButtonVisible.value = false
                } else {
                    Log.d("cobaaja", answerString)
                    val checkData = checkAnswer(answerString);
                    if (checkData) {
                        triggerSnackbar("Jawaban Benar")
                    } else {
                        triggerSnackbar("Jawaban Salah")
                    }
                    _isButtonVisible.value = true
                }
            }
        }
    }

    private val _snackbarMessage = MutableStateFlow<String?>(null)
    val snackbarMessage: StateFlow<String?> = _snackbarMessage

    fun triggerSnackbar(message: String) {
        _snackbarMessage.value = message
    }

    fun onSnackbarShown() {
        _snackbarMessage.value = null
    }

    override fun onCleared() {
        tts?.stop()
        tts?.shutdown()
        super.onCleared()
    }
}