package com.example.petstoremobile.adapters;

import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.petstoremobile.databinding.ItemChatBinding;
import com.example.petstoremobile.models.Chat;

import java.util.List;

public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ChatViewHolder> {

    private List<Chat> chatList;
    private OnChatClickListener listener;

    public interface OnChatClickListener {
        void onChatClick(Chat chat);
    }

    /**
     * Constructor for ChatAdapter.
     */
    public ChatAdapter(List<Chat> chatList, OnChatClickListener listener) {
        this.chatList = chatList;
        this.listener = listener;
    }

    /**
     * Inflates the layout for a chat item and creates the ViewHolder.
     */
    @NonNull
    @Override
    public ChatViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemChatBinding binding = ItemChatBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
        return new ChatViewHolder(binding);
    }

    /**
     * Binds chat data to the UI components for a specific conversation.
     */
    @Override
    public void onBindViewHolder(@NonNull ChatViewHolder holder, int position) {
        Chat chat = chatList.get(position);
        holder.binding.tvCustomerName.setText(chat.getCustomerName());
        holder.binding.tvLastMessage.setText(chat.getLastMessage());
        holder.itemView.setOnClickListener(v -> listener.onChatClick(chat));
    }

    /**
     * Returns the total number of chat items in the list.
     */
    @Override
    public int getItemCount() {
        return chatList.size();
    }

    /**
     * ViewHolder class that holds references to the UI components for a chat item.
     */
    public static class ChatViewHolder extends RecyclerView.ViewHolder {
        final ItemChatBinding binding;

        /**
         * Initializes the ViewHolder with the chat item's view binding.
         */
        public ChatViewHolder(@NonNull ItemChatBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }
}