package com.rugvedsarika.easymath.ui.practice

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

class PracticeFragment : Fragment() {

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

    private lateinit var viewModel: MathViewModel

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentPracticeBinding.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]

        // Arguments (category, level)
        val category = arguments?.getString("category") ?: "Addition"
        val level = arguments?.getString("level") ?: "Easy"

        viewModel.startGame(category, level)

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

        viewModel.score.observe(viewLifecycleOwner) { score ->
            binding.textScore.text = "Score: $score"
        }
        
        viewModel.totalQuestions.observe(viewLifecycleOwner) { total ->
            binding.textQuestionCount.text = "Q: ${total + 1}"
        }

        binding.btnSubmit.setOnClickListener {
            checkAnswer()
        }

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

    private fun checkAnswer() {
        val answerText = binding.editAnswer.text.toString()
        if (answerText.isNotEmpty()) {
            val answer = answerText.toIntOrNull()
            if (answer != null) {
                val isCorrect = viewModel.checkAnswer(answer)
                if (isCorrect) {
                    binding.textFeedback.text = "Correct!"
                    binding.textFeedback.setTextColor(ContextCompat.getColor(requireContext(), R.color.correct_green))
                    viewModel.loadNextQuestion()
                } else {
                    binding.textFeedback.text = "Wrong!"
                    binding.textFeedback.setTextColor(ContextCompat.getColor(requireContext(), R.color.wrong_red))
                    // Could delay next question or ask to try again
                    // For now, load next after short delay or let user correct?
                    // Let's standardise: Instant feedback, then next question after delay?
                    // For simplicity, let's just show wrong and load next.
                    binding.editAnswer.postDelayed({
                        viewModel.loadNextQuestion()
                    }, 1000)
                }
            }
        }
    }

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