package com.divyagkquiz.app.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.divyagkquiz.app.R
import com.divyagkquiz.app.viewmodel.QuizViewModel

class HomeFragment : Fragment() {

    private val viewModel: QuizViewModel by viewModels()
    private lateinit var categoryAdapter: CategoryAdapter

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_home, container, false)
    }

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

        val dailyQuestionCard = view.findViewById<View>(R.id.daily_question_card)
        val categoriesRecyclerView = view.findViewById<RecyclerView>(R.id.categories_recycler_view)

        // Setup Categories
        val categories = listOf(
            "General Knowledge", "Science", "History", "Geography", 
            "Sports", "Current Affairs", "Technology", "Movies & TV", 
            "Literature", "Space", "Nature", "Art & Culture"
        )
        categoryAdapter = CategoryAdapter(categories) { category ->
            val bundle = Bundle().apply {
                putString("category", category)
            }
            findNavController().navigate(R.id.action_home_to_quiz, bundle)
        }
        categoriesRecyclerView.layoutManager = GridLayoutManager(context, 2)
        categoriesRecyclerView.isNestedScrollingEnabled = false
        categoriesRecyclerView.adapter = categoryAdapter

        // Daily Question Logic
        viewModel.dailyQuestion.observe(viewLifecycleOwner) { question ->
            if (question != null) {
                view.findViewById<TextView>(R.id.daily_question_text).text = question.question
                dailyQuestionCard.setOnClickListener {
                    val bundle = Bundle().apply {
                         putString("category", "Daily")
                    }
                    findNavController().navigate(R.id.action_home_to_quiz, bundle)
                }
            }
        }
    }
}
