package com.unibuy.smartdevice.ui.recycler;

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 com.unibuy.smartdevice.R;

import java.util.List;

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

    private List<String> organizationNames;
    private int selectedPosition = -1;
    private OnItemClickListener listener;

    public interface OnItemClickListener {
        void onItemClick(String name, int position);
    }

    public RecyclerDonationListAdpter(List<String> organizationNames, OnItemClickListener listener) {
        this.organizationNames = organizationNames;
        this.listener = listener;
    }

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

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        String name = organizationNames.get(position);
        holder.textView.setText(name);

        // 高亮選中項
        if (position == selectedPosition) {
            holder.textView.setBackgroundResource(R.drawable.bg_selected_item);
            holder.textView.setTextColor(holder.itemView.getContext().getResources().getColor(R.color.white));
        } else {
            holder.textView.setBackgroundResource(android.R.color.transparent);
            holder.textView.setTextColor(holder.itemView.getContext().getResources().getColor(R.color.black));
        }

        holder.itemView.setOnClickListener(v -> {
            int previousPosition = selectedPosition;
            selectedPosition = position;
            notifyItemChanged(previousPosition);
            notifyItemChanged(selectedPosition);
            if (listener != null) {
                listener.onItemClick(name, position);
            }
        });
    }

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

    public void setSelectedPosition(int position) {
        this.selectedPosition = position;
        notifyDataSetChanged();
    }

    public int getSelectedPosition() {
        return selectedPosition;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView textView;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.spinnerText);
        }
    }
}
