package com.divyagkquiz.app.ui

import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.content.Context
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.google.android.material.button.MaterialButton
import com.google.android.material.progressindicator.LinearProgressIndicator
import com.divyagkquiz.app.R
import com.divyagkquiz.app.viewmodel.QuizViewModel
import com.divyagkquiz.app.data.Question

class QuizFragment : Fragment() {

    private val viewModel: QuizViewModel by viewModels()
    private lateinit var questionText: TextView
    private lateinit var option1: MaterialButton
    private lateinit var option2: MaterialButton
    private lateinit var option3: MaterialButton
    private lateinit var option4: MaterialButton
    private lateinit var nextButton: MaterialButton
    private lateinit var questionCounter: TextView
    private lateinit var timerText: TextView
    private lateinit var timerProgress: LinearProgressIndicator
    private lateinit var explanationText: TextView

    private var selectedOptionIndex: Int = -1
    private var isAnswered = false

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_quiz, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        questionText = view.findViewById(R.id.question_text)
        option1 = view.findViewById(R.id.option1)
        option2 = view.findViewById(R.id.option2)
        option3 = view.findViewById(R.id.option3)
        option4 = view.findViewById(R.id.option4)
        nextButton = view.findViewById(R.id.next_button)
        questionCounter = view.findViewById(R.id.question_counter)
        timerText = view.findViewById(R.id.timer_text)
        timerProgress = view.findViewById(R.id.timer_progress)
        explanationText = view.findViewById(R.id.explanation_text)

        val category = arguments?.getString("category") ?: "All"
        viewModel.startQuiz(category)

        val options = listOf(option1, option2, option3, option4)

        options.forEachIndexed { index, button ->
            button.setOnClickListener {
                if (!isAnswered) {
                    selectedOptionIndex = index
                    viewModel.answerQuestion(index)
                    checkAnswer(index)
                }
            }
        }

        nextButton.setOnClickListener {
            viewModel.moveToNext()
        }

        viewModel.currentQuestionIndex.observe(viewLifecycleOwner) { index ->
            val questions = viewModel.questions.value
            if (questions != null && index < questions.size) {
                updateQuestionUI(questions[index], index + 1, questions.size)
            }
        }

        viewModel.timerValue.observe(viewLifecycleOwner) { seconds ->
            timerText.text = "${seconds}s"
            timerProgress.progress = (seconds * 100) / 15
            if (seconds == 0 && !isAnswered) {
                checkAnswer(-1) // Time out
            }
        }

        viewModel.vibrateTrigger.observe(viewLifecycleOwner) { trigger ->
            if (trigger) {
                triggerVibration()
            }
        }

        viewModel.quizFinished.observe(viewLifecycleOwner) { finished ->
            if (finished) {
                val score = viewModel.score.value ?: 0
                val total = viewModel.questions.value?.size ?: 0
                val category = arguments?.getString("category") ?: "All"
                val isNew = viewModel.isNewRecord.value ?: false
                val bundle = Bundle().apply {
                    putInt("score", score)
                    putInt("total", total)
                    putString("category", category)
                    putBoolean("isNewRecord", isNew)
                }
                findNavController().navigate(R.id.action_quizFragment_to_resultFragment, bundle)
            }
        }
    }

    private fun triggerVibration() {
        val vibrator = requireContext().getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            vibrator.vibrate(VibrationEffect.createOneShot(100, VibrationEffect.DEFAULT_AMPLITUDE))
        } else {
            vibrator.vibrate(100)
        }
    }

    private fun updateQuestionUI(question: Question, index: Int, total: Int) {
        questionText.text = question.question
        questionCounter.text = "Question $index/$total"
        explanationText.visibility = View.GONE
        explanationText.text = question.explanation
        
        val options = listOf(option1, option2, option3, option4)
        options.forEachIndexed { i, button ->
            button.text = question.options[i]
            button.isEnabled = true
            button.setBackgroundColor(Color.TRANSPARENT) 
            button.setTextColor(ContextCompat.getColor(requireContext(), R.color.primary_color))
            button.strokeColor = ContextCompat.getColorStateList(requireContext(), R.color.primary_color)
            button.strokeWidth = 2
        }
        
        isAnswered = false
        selectedOptionIndex = -1
        nextButton.visibility = View.GONE
    }

    private fun checkAnswer(selectedIndex: Int) {
        isAnswered = true
        val questions = viewModel.questions.value ?: return
        val index = viewModel.currentQuestionIndex.value ?: return
        val currentQuestion = questions[index]
        
        val options = listOf(option1, option2, option3, option4)
        val correctColor = ContextCompat.getColor(requireContext(), R.color.correct_green)
        val wrongColor = ContextCompat.getColor(requireContext(), R.color.wrong_red)
        val whiteColor = ContextCompat.getColor(requireContext(), R.color.white)
        
        if (selectedIndex != -1) {
            if (selectedIndex == currentQuestion.correctAnswerIndex) {
                options[selectedIndex].setBackgroundColor(correctColor)
                options[selectedIndex].setTextColor(whiteColor)
            } else {
                options[selectedIndex].setBackgroundColor(wrongColor)
                options[selectedIndex].setTextColor(whiteColor)
                options[currentQuestion.correctAnswerIndex].setBackgroundColor(correctColor)
                options[currentQuestion.correctAnswerIndex].setTextColor(whiteColor)
            }
        } else {
            options[currentQuestion.correctAnswerIndex].setBackgroundColor(correctColor)
            options[currentQuestion.correctAnswerIndex].setTextColor(whiteColor)
        }

        if (currentQuestion.explanation.isNotEmpty()) {
            explanationText.visibility = View.VISIBLE
        }

        options.forEach { it.isEnabled = false }
        nextButton.visibility = View.VISIBLE
    }
}
