package com.rugvedsarika.easymath.ui.speed

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.rugvedsarika.easymath.EasyMathApp
import com.rugvedsarika.easymath.R
import com.rugvedsarika.easymath.databinding.FragmentSpeedChallengeBinding
import com.rugvedsarika.easymath.viewmodel.MathViewModel
import com.rugvedsarika.easymath.viewmodel.MathViewModelFactory

class SpeedChallengeFragment : Fragment() {

    private var _binding: FragmentSpeedChallengeBinding? = null
    private val binding get() = _binding!!

    private lateinit var viewModel: MathViewModel

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentSpeedChallengeBinding.inflate(inflater, container, false)
        return binding.root
    }

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

        val app = requireActivity().application as EasyMathApp
        val factory = MathViewModelFactory(app.repository, app.audioManager)
        viewModel = ViewModelProvider(this, factory)[MathViewModel::class.java]

        // 60 seconds speed challenge
        viewModel.startGame("Speed_Challenge", "Medium", 60000)

        viewModel.currentQuestion.observe(viewLifecycleOwner) { question ->
            binding.textQuestion.text = question.text
            binding.editAnswer.text.clear()
        }

        viewModel.score.observe(viewLifecycleOwner) { score ->
            binding.textScore.text = "Score: $score"
        }
        
        viewModel.timeLeft.observe(viewLifecycleOwner) { seconds ->
            binding.textTimer.text = "${seconds}s"
            if (seconds <= 10) {
                 binding.textTimer.setTextColor(ContextCompat.getColor(requireContext(), R.color.wrong_red))
            } else {
                 binding.textTimer.setTextColor(ContextCompat.getColor(requireContext(), R.color.primary))
            }
        }
        
        viewModel.isGameFinished.observe(viewLifecycleOwner) { finished ->
            if (finished) {
                Toast.makeText(context, "Time's up! Final Score: ${viewModel.score.value}", Toast.LENGTH_LONG).show()
                findNavController().popBackStack()
            }
        }

        binding.btnSubmit.setOnClickListener {
            checkAnswer()
        }

        binding.editAnswer.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                checkAnswer()
                true
            } else {
                false
            }
        }
    }

    private fun checkAnswer() {
        if (viewModel.isGameFinished.value == true) return

        val answerText = binding.editAnswer.text.toString()
        if (answerText.isNotEmpty()) {
            val answer = answerText.toIntOrNull()
            if (answer != null) {
                val isCorrect = viewModel.checkAnswer(answer)
                if (isCorrect) {
                     // Maybe flash green?
                } else {
                     // Maybe flash red?
                }
                viewModel.loadNextQuestion()
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}
