package com.rugvedsarika.easymath.ui.progress

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.fragment.app.activityViewModels
import com.rugvedsarika.easymath.EasyMathApp
import com.rugvedsarika.easymath.databinding.FragmentProgressBinding
import com.rugvedsarika.easymath.viewmodel.MathViewModel
import com.rugvedsarika.easymath.viewmodel.MathViewModelFactory
import kotlinx.coroutines.launch

class ProgressFragment : Fragment() {

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

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

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

        // Use activityViewModels to share the instance with ProfileSelectionFragment
        val viewModel: MathViewModel by activityViewModels {
            val app = requireActivity().application as EasyMathApp
            MathViewModelFactory(app.repository, app.audioManager)
        }
        
        val adapter = HistoryAdapter()
        binding.recyclerHistory.adapter = adapter

        // Observe LiveData from ViewModel
        viewModel.history.observe(viewLifecycleOwner) { list ->
            adapter.submitList(list)
        }
        
        viewModel.accuracy.observe(viewLifecycleOwner) { accuracy ->
             binding.textOverallAccuracy.text = "%.0f%%".format(accuracy ?: 0f)
        }
    }

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