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.ItemPurchaseOrderBinding;
import com.example.petstoremobile.dtos.PurchaseOrderDTO;
import java.util.List;

public class PurchaseOrderAdapter extends RecyclerView.Adapter<PurchaseOrderAdapter.POViewHolder> {

    private List<PurchaseOrderDTO> list;
    private OnPurchaseOrderClickListener listener;

    public interface OnPurchaseOrderClickListener {
        void onPurchaseOrderClick(int position);
    }

    /**
     * Constructor for PurchaseOrderAdapter.
     */
    public PurchaseOrderAdapter(List<PurchaseOrderDTO> list, OnPurchaseOrderClickListener listener) {
        this.list = list;
        this.listener = listener;
    }

    /**
     * ViewHolder for Purchase Order items.
     */
    public static class POViewHolder extends RecyclerView.ViewHolder {
        final ItemPurchaseOrderBinding binding;

        /**
         * Initializes the ViewHolder with view binding.
         */
        public POViewHolder(@NonNull ItemPurchaseOrderBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }

    /**
     * Inflates the layout for a Purchase Order item.
     */
    @NonNull
    @Override
    public POViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemPurchaseOrderBinding binding = ItemPurchaseOrderBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
        return new POViewHolder(binding);
    }

    /**
     * Binds purchase order data to the UI components.
     */
    @Override
    public void onBindViewHolder(@NonNull POViewHolder holder, int position) {
        PurchaseOrderDTO po = list.get(position);
        ItemPurchaseOrderBinding binding = holder.binding;

        binding.tvPOId.setText("PO #" + (po.getPurchaseOrderId() != null ? po.getPurchaseOrderId() : ""));
        binding.tvPOSupplier.setText("Supplier: " + (po.getSupplierName() != null ? po.getSupplierName() : ""));
        binding.tvPOStore.setText("Store: " + (po.getStoreName() != null ? po.getStoreName() : ""));
        binding.tvPODate.setText("Date: " + (po.getOrderDate() != null ? po.getOrderDate() : ""));

        holder.itemView.setOnClickListener(v -> listener.onPurchaseOrderClick(position));
    }

    @Override
    public int getItemCount() {
        return list.size();
    }
}