package com.rugvedsarika.easymath.ui.achievements

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import com.rugvedsarika.easymath.EasyMathApp
import com.rugvedsarika.easymath.databinding.FragmentAchievementsBinding
import com.rugvedsarika.easymath.utils.AchievementManager
import com.rugvedsarika.easymath.viewmodel.MathViewModel
import com.rugvedsarika.easymath.viewmodel.MathViewModelFactory

class AchievementsFragment : Fragment() {

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

    private val viewModel: MathViewModel by viewModels {
        val app = requireActivity().application as EasyMathApp
        MathViewModelFactory(app.repository, app.audioManager)
    }

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

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

        val adapter = AchievementsAdapter()
        binding.recyclerAchievements.layoutManager = GridLayoutManager(context, 1) // List for now
        binding.recyclerAchievements.adapter = adapter

        // Combine static definitions with unlocked status from DB
        viewModel.achievements.observe(viewLifecycleOwner) { unlockedList ->
            val allAchievements = AchievementManager.ALL_ACHIEVEMENTS.map { staticDef ->
                val unlockedItem = unlockedList.find { it.code == staticDef.code }
                if (unlockedItem != null) {
                    staticDef.copy(unlocked = true, timestamp = unlockedItem.timestamp)
                } else {
                    staticDef
                }
            }
            adapter.submitList(allAchievements)
            
            // Update progress
            val unlockedCount = unlockedList.size
            val total = AchievementManager.ALL_ACHIEVEMENTS.size
            binding.progressAchievements.max = total
            binding.progressAchievements.progress = unlockedCount
            binding.textProgressLabel.text = "$unlockedCount/$total Unlocked"
        }
    }

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