package com.example.pap_teste;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;

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

import com.example.pap_teste.models.Review;

import java.util.List;

public class ReviewAdapter extends RecyclerView.Adapter<ReviewAdapter.ViewHolder> {
    private List<Review> reviews;
    private String currentUserEmail;
    private OnReviewDeleteListener deleteListener;

    public interface OnReviewDeleteListener {
        void onDeleteClick(Review review);
    }

    public ReviewAdapter(List<Review> reviews, String currentUserEmail, OnReviewDeleteListener deleteListener) {
        this.reviews = reviews;
        this.currentUserEmail = currentUserEmail;
        this.deleteListener = deleteListener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_review, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Review review = reviews.get(position);
        
        holder.txtAuthor.setText(review.getAuthor() != null ? review.getAuthor() : "Anónimo");
        holder.txtText.setText(review.getText() != null ? review.getText() : "");
        holder.txtRating.setText(String.valueOf(review.getRating()));

        if (currentUserEmail != null && currentUserEmail.equals(review.getUserEmail())) {
            holder.btnDelete.setVisibility(View.VISIBLE);
            holder.btnDelete.setOnClickListener(v -> {
                if (deleteListener != null) {
                    deleteListener.onDeleteClick(review);
                }
            });
        } else {
            holder.btnDelete.setVisibility(View.GONE);
        }
    }

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

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView txtAuthor, txtText, txtRating;
        ImageButton btnDelete;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            txtAuthor = itemView.findViewById(R.id.txtReviewAuthor);
            txtText = itemView.findViewById(R.id.txtReviewText);
            txtRating = itemView.findViewById(R.id.txtReviewRating);
            btnDelete = itemView.findViewById(R.id.btnDeleteReview);
        }
    }
}
