package com.rugvedsarika.shoplist.ui.home

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.rugvedsarika.shoplist.data.local.entities.ShoppingList
import com.rugvedsarika.shoplist.databinding.ItemShoppingListBinding
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class ShoppingListAdapter(
    private val onItemClicked: (ShoppingList) -> Unit,
    private val onEditClicked: (ShoppingList) -> Unit,
    private val onDeleteClicked: (ShoppingList) -> Unit
) : ListAdapter<ShoppingList, ShoppingListAdapter.ShoppingListViewHolder>(ShoppingListDiffCallback()) {

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

    override fun onBindViewHolder(holder: ShoppingListViewHolder, position: Int) {
        val item = getItem(position)
        holder.bind(item)
    }

    inner class ShoppingListViewHolder(private val binding: ItemShoppingListBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(item: ShoppingList) {
            binding.tvListName.text = item.name
            val dateFormat = SimpleDateFormat("dd MMM yyyy", Locale.getDefault())
            binding.tvDate.text = "Created on ${dateFormat.format(Date(item.createdAt))}"

            binding.root.setOnClickListener {
                onItemClicked(item)
            }

            binding.btnEdit.setOnClickListener {
                onEditClicked(item)
            }

            binding.btnDelete.setOnClickListener {
                onDeleteClicked(item)
            }
        }
    }

    class ShoppingListDiffCallback : DiffUtil.ItemCallback<ShoppingList>() {
        override fun areItemsTheSame(oldItem: ShoppingList, newItem: ShoppingList): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: ShoppingList, newItem: ShoppingList): Boolean {
            return oldItem == newItem
        }
    }
}
