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.ItemHardwareBinding
import com.divya.hardinfo.model.HardwareItem

class HardwareAdapter(private val onItemClick: (HardwareItem) -> Unit) :
    ListAdapter<HardwareItem, HardwareAdapter.HardwareViewHolder>(HardwareDiffCallback()) {

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

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

    inner class HardwareViewHolder(private val binding: ItemHardwareBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(item: HardwareItem) {
            binding.textItemName.text = item.name
            binding.textItemDesc.text = item.description
            
            // In a real app, we would load image dynamically. 
             val formattedName = item.imageRes.replace("@drawable/", "").replace(".png", "")
             val resId = binding.root.context.resources.getIdentifier(formattedName, "drawable", binding.root.context.packageName)
             if (resId != 0) {
                 binding.imgItem.setImageResource(resId)
             } else {
                 binding.imgItem.setImageResource(android.R.drawable.ic_menu_info_details)
             }

            binding.root.setOnClickListener { onItemClick(item) }
        }
    }

    class HardwareDiffCallback : DiffUtil.ItemCallback<HardwareItem>() {
        override fun areItemsTheSame(oldItem: HardwareItem, newItem: HardwareItem) = oldItem.id == newItem.id
        override fun areContentsTheSame(oldItem: HardwareItem, newItem: HardwareItem) = oldItem == newItem
    }
}
