package com.divyagkquiz.app.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.divyagkquiz.app.data.Question
import com.divyagkquiz.app.data.QuizRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

import android.content.Context
import android.content.SharedPreferences
import android.os.CountDownTimer

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

    private val repository = QuizRepository(application)
    private val prefs: SharedPreferences = application.getSharedPreferences("gk_master_prefs", Context.MODE_PRIVATE)
    
    private val _questions = MutableLiveData<List<Question>>()
    val questions: LiveData<List<Question>> = _questions

    private val _currentQuestionIndex = MutableLiveData(0)
    val currentQuestionIndex: LiveData<Int> = _currentQuestionIndex
    
    private val _score = MutableLiveData(0)
    val score: LiveData<Int> = _score
    
    private val _quizFinished = MutableLiveData(false)
    val quizFinished: LiveData<Boolean> = _quizFinished

    private val _dailyQuestion = MutableLiveData<Question?>()
    val dailyQuestion: LiveData<Question?> = _dailyQuestion

    // Timer logic
    private val _timerValue = MutableLiveData(15)
    val timerValue: LiveData<Int> = _timerValue
    private var timer: CountDownTimer? = null

    // Haptic/Sound triggers
    private val _vibrateTrigger = MutableLiveData<Boolean>()
    val vibrateTrigger: LiveData<Boolean> = _vibrateTrigger

    private val _isNewRecord = MutableLiveData(false)
    val isNewRecord: LiveData<Boolean> = _isNewRecord

    private var currentCategory: String = "All"

    fun getCategoryCounts(): Map<String, Int> {
        return repository.getCategoryCounts()
    }

    init {
        loadDailyQuestion()
    }

    fun loadDailyQuestion() {
        viewModelScope.launch(Dispatchers.IO) {
            val q = repository.getDailyQuestion()
            withContext(Dispatchers.Main) {
                _dailyQuestion.value = q
            }
        }
    }

    fun startQuiz(category: String) {
        currentCategory = category
        viewModelScope.launch(Dispatchers.IO) {
            val allQuestions = repository.getQuestions()
            val filteredQuestions = when (category) {
                "All" -> allQuestions.shuffled().take(10)
                "Daily" -> {
                    val daily = repository.getDailyQuestion()
                    if (daily != null) listOf(daily) else emptyList()
                }
                else -> allQuestions.filter { it.category == category }.shuffled().take(10)
            }
            withContext(Dispatchers.Main) {
                _questions.value = filteredQuestions
                _currentQuestionIndex.value = 0
                _score.value = 0
                _quizFinished.value = false
                _isNewRecord.value = false
                startTimer()
            }
        }
    }

    private fun startTimer() {
        timer?.cancel()
        _timerValue.value = 15
        timer = object : CountDownTimer(15000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                _timerValue.value = (millisUntilFinished / 1000).toInt()
            }

            override fun onFinish() {
                _timerValue.value = 0
                answerQuestion(-1) // Time out
            }
        }.start()
    }

    fun answerQuestion(selectedIndex: Int) {
        timer?.cancel()
        val questionsList = _questions.value ?: return
        val currentIndex = _currentQuestionIndex.value ?: 0
        
        if (currentIndex < questionsList.size) {
            if (questionsList[currentIndex].correctAnswerIndex == selectedIndex) {
                _score.value = (_score.value ?: 0) + 1
            } else {
                _vibrateTrigger.value = true // Trigger shake/vibe for wrong answer
            }
            
            // Wait for fragment to show explanation before moving next (handled in fragment)
        }
    }

    fun moveToNext() {
        val currentIndex = _currentQuestionIndex.value ?: 0
        val questionsList = _questions.value ?: return
        
        if (currentIndex + 1 < questionsList.size) {
            _currentQuestionIndex.value = currentIndex + 1
            startTimer()
        } else {
            saveHighScore()
            _quizFinished.value = true
        }
    }

    private fun saveHighScore() {
        val currentScore = _score.value ?: 0
        val key = "high_score_$currentCategory"
        val existingHighScore = prefs.getInt(key, 0)
        
        val editor = prefs.edit()
        
        // Save category specific high score
        if (currentScore > existingHighScore) {
            editor.putInt(key, currentScore)
            _isNewRecord.value = true
        }
        
        // Save career stats
        val totalQuizzes = prefs.getInt("total_quizzes", 0) + 1
        val totalScore = prefs.getInt("total_score", 0) + currentScore
        editor.putInt("total_quizzes", totalQuizzes)
        editor.putInt("total_score", totalScore)
        
        // Use commit() for high scores to ensure it's saved before navigation
        editor.commit()
    }

    fun getHighScore(category: String): Int {
        return prefs.getInt("high_score_$category", 0)
    }

    fun getCareerStats(): Pair<Int, Int> {
        return Pair(
            prefs.getInt("total_quizzes", 0),
            prefs.getInt("total_score", 0)
        )
    }

    override fun onCleared() {
        super.onCleared()
        timer?.cancel()
    }
}
