package com.divya.hardinfo.ui

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.divya.hardinfo.databinding.ItemCategoryBinding
import com.divya.hardinfo.model.Category
import com.divya.hardinfo.R

class CategoriesAdapter(private val onCategoryClick: (String) -> Unit) :
    ListAdapter<Category, CategoriesAdapter.CategoryViewHolder>(CategoryDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoryViewHolder {
        val binding = ItemCategoryBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return CategoryViewHolder(binding)
    }

    override fun onBindViewHolder(holder: CategoryViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    inner class CategoryViewHolder(private val binding: ItemCategoryBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(category: Category) {
            binding.textCategoryName.text = category.name
            binding.textCategoryDesc.text = category.description
            
            val context = binding.root.context
            val resourceId = context.resources.getIdentifier(
                category.imageRes, 
                "drawable", 
                context.packageName
            )
            
            if (resourceId != 0) {
                binding.imgCategory.setImageResource(resourceId)
            } else {
                binding.imgCategory.setImageResource(R.mipmap.ic_launcher) // Fallback
            }
            
            binding.root.setOnClickListener { onCategoryClick(category.name) }
        }
    }

    class CategoryDiffCallback : DiffUtil.ItemCallback<Category>() {
        override fun areItemsTheSame(oldItem: Category, newItem: Category) = oldItem.name == newItem.name
        override fun areContentsTheSame(oldItem: Category, newItem: Category) = oldItem == newItem
    }
}
