package com.rugvedsarika.easymath.ui.exam

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.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.rugvedsarika.easymath.EasyMathApp
import com.rugvedsarika.easymath.R
import com.rugvedsarika.easymath.databinding.FragmentExamBinding
import com.rugvedsarika.easymath.viewmodel.MathViewModel
import com.rugvedsarika.easymath.viewmodel.MathViewModelFactory

class ExamFragment : Fragment() {

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

    private val viewModel: MathViewModel by viewModels {
        val app = requireActivity().application as EasyMathApp
        MathViewModelFactory(app.repository, app.audioManager)
    }
    
    // Exam specific state
    private val maxQuestions = 20

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

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

        // Start Exam Mode
        viewModel.startGame("Exam", "Medium") 

        viewModel.currentQuestion.observe(viewLifecycleOwner) { question ->
            binding.textQuestion.text = question.text
            binding.editAnswer.text?.clear()
        }
        
        viewModel.totalQuestions.observe(viewLifecycleOwner) { total ->
            binding.textProgress.text = "Question ${total + 1} / $maxQuestions"
        }

        binding.btnSubmit.setOnClickListener {
            submitAnswer()
        }

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

    private fun submitAnswer() {
        val answerText = binding.editAnswer.text.toString()
        if (answerText.isNotEmpty()) {
            val answer = answerText.toIntOrNull()
            if (answer != null) {
                // Check answer (this updates score internally but suppresses sound/feedback due to isExamMode)
                viewModel.checkAnswer(answer)
                
                // Check if exam finished
                val total = (viewModel.totalQuestions.value ?: 0)
                if (total >= maxQuestions) {
                    finishExam()
                } else {
                    viewModel.loadNextQuestion()
                }
            }
        }
    }

    private fun finishExam() {
        // Save session is called automatically? No, only on timer finish or manually ??
        // In MathViewModel, saveSession is exposed.
        viewModel.saveSession()
        
        // Navigate to Result
        // For now, simpler: Toast and pop
        Toast.makeText(context, "Exam Finished! Score: ${viewModel.score.value}/$maxQuestions", Toast.LENGTH_LONG).show()
        findNavController().popBackStack()
    }

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