package com.example.lexilearn.ui.views.pNavMaterial

import android.app.Application
import android.speech.tts.TextToSpeech
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.repository.MaterialRepository
import com.example.lexilearn.data.repository.UserRepository
import com.example.lexilearn.utils.generateNumberList
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import java.util.*

class NavMaterialViewModel(application: Application) : AndroidViewModel(application),
    TextToSpeech.OnInitListener {

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

    private val _textTitle = MutableLiveData("Hello, Jetpack Compose!")
    val textTitle: LiveData<String> = _textTitle

    private val _sizeUnlock = MutableLiveData(0)
    val sizeUnlock: LiveData<Int> = _sizeUnlock

    private val _navLockPosition = MutableStateFlow(-1)
    val navLockPosition: StateFlow<Int> = _navLockPosition

    private val repository = MaterialRepository(application)
    private val userRepository = UserRepository(application)

    private val _materialList = MutableStateFlow<List<List<MaterialDataModel>>>(emptyList())
    val materialList: StateFlow<List<List<MaterialDataModel>>> = _materialList

    fun fetchMaterial(materialId: String) {
        viewModelScope.launch {
            userRepository.getUnlockValue(materialId) { value ->
                _sizeUnlock.value = value
            }
            repository.getMaterialData(materialId) { materials ->
                _materialList.value = materials.chunked(3)
                if (materials[0].category == "animal") {
                    _textTitle.value = "hewan"
                } else if (materials[0].category == "limb") {
                    _textTitle.value = "anggota tubuh"
                } else if (materials[0].category == "house") {
                    _textTitle.value = "bagian rumah"
                } else if (materials[0].category == "family") {
                    _textTitle.value = "anggota keluarga"
                }
            }
        }
    }

    init {
        tts = TextToSpeech(application, this)
    }

    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 updateUnlockValue(materialId: String, value: Int) {
        if(value >= (_sizeUnlock.value ?: 0) && _materialList.value.size > value){
            viewModelScope.launch {
                userRepository.updateUnlockData(materialId, value){
                    println("numberUnlock update unlock value success $it")
                    fetchMaterial(materialId)
                }
                _navLockPosition.value = value
                delay(1800)
                _navLockPosition.value = -1
            }
        }else{
            println("numberUnlock-else $value, ${_sizeUnlock.value}, ${_materialList.value.size}")
        }
    }

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