package com.example.pap_teste;

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

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

import java.util.List;

public class ReservationOptionAdapter extends RecyclerView.Adapter<ReservationOptionAdapter.ViewHolder> {

    public interface OnOptionSelectedListener {
        void onOptionSelected(String option);
    }

    private final List<String> options;
    private final OnOptionSelectedListener listener;
    private int selectedPosition = -1;

    public ReservationOptionAdapter(List<String> options, OnOptionSelectedListener listener) {
        this.options = options;
        this.listener = listener;
    }

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

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        String option = options.get(position);
        holder.txtValue.setText(option);

        boolean isSelected = position == selectedPosition;
        holder.cardRoot.setCardBackgroundColor(isSelected ? 0xFFFF6B6B : 0xFFFFFFFF);
        holder.txtValue.setTextColor(isSelected ? 0xFFFFFFFF : 0xFF000000);

        holder.itemView.setOnClickListener(v -> {
            int previousSelected = selectedPosition;
            selectedPosition = holder.getAdapterPosition();
            notifyItemChanged(previousSelected);
            notifyItemChanged(selectedPosition);
            if (listener != null) {
                listener.onOptionSelected(option);
            }
        });
    }

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

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView txtValue;
        androidx.cardview.widget.CardView cardRoot;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            txtValue = itemView.findViewById(R.id.txtOptionValue);
            cardRoot = itemView.findViewById(R.id.cardOption);
        }
    }
}
