package com.example.petstoremobile.adapters;

import android.view.*;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.petstoremobile.R;
import com.example.petstoremobile.api.ProductApi;
import com.example.petstoremobile.databinding.ItemProductBinding;
import com.example.petstoremobile.dtos.ProductDTO;
import com.example.petstoremobile.utils.GlideUtils;
import java.util.List;

public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {

    private List<ProductDTO> productList;
    private OnProductClickListener listener;
    private String baseUrl;
    private String token;

    public interface OnProductClickListener {
        void onProductClick(int position);
    }

    public ProductAdapter(List<ProductDTO> productList, OnProductClickListener listener) {
        this.productList = productList;
        this.listener = listener;
    }

    public void setBaseUrl(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public static class ProductViewHolder extends RecyclerView.ViewHolder {
        final ItemProductBinding binding;

        public ProductViewHolder(@NonNull ItemProductBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }

    @NonNull
    @Override
    public ProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemProductBinding binding = ItemProductBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
        return new ProductViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull ProductViewHolder holder, int position) {
        ProductDTO p = productList.get(position);
        ItemProductBinding binding = holder.binding;

        binding.tvProductName.setText(p.getProdName() != null ? p.getProdName() : "");
        binding.tvProductCategory.setText("Category: " + (p.getCategoryName() != null ? p.getCategoryName() : ""));
        binding.tvProductDesc.setText(p.getProdDesc() != null ? p.getProdDesc() : "");
        binding.tvProductPrice.setText(p.getProdPrice() != null ? "$" + p.getProdPrice() : "");

        // Load product image using Glide
        if (baseUrl != null) {
            String imageUrl = baseUrl + String.format(ProductApi.PRODUCT_IMAGE_PATH, p.getProdId());
            GlideUtils.loadImageWithTokenCircle(holder.itemView.getContext(), binding.ivProductImage, imageUrl, token, R.drawable.placeholder);
        } else {
            binding.ivProductImage.setImageResource(R.drawable.placeholder);
        }

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

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