package com.example.cuida.ui.schedule;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.cuida.R;
import com.google.android.material.button.MaterialButton;
import java.util.ArrayList;
import java.util.List;

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

    private List<TimeSlot> timeSlots = new ArrayList<>();
    private OnTimeSlotSelectedListener listener;

    public interface OnTimeSlotSelectedListener {
        void onTimeSlotSelected(String time);
    }

    public void setOnTimeSlotSelectedListener(OnTimeSlotSelectedListener listener) {
        this.listener = listener;
    }

    public void setTimeSlots(List<TimeSlot> slots) {
        this.timeSlots = slots;
        notifyDataSetChanged();
    }

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

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        TimeSlot slot = timeSlots.get(position);
        holder.btnTimeSlot.setText(slot.getTime());

        if (slot.isBooked()) {
            holder.btnTimeSlot.setEnabled(false);
            holder.btnTimeSlot.setAlpha(0.5f);
            holder.btnTimeSlot.setChecked(false);
            holder.btnTimeSlot.setOnClickListener(null);
        } else {
            holder.btnTimeSlot.setEnabled(true);
            holder.btnTimeSlot.setAlpha(1.0f);
            holder.btnTimeSlot.setChecked(slot.isSelected());

            holder.btnTimeSlot.setOnClickListener(v -> {
                if (listener != null) {
                    listener.onTimeSlotSelected(slot.getTime());
                }
            });
        }
    }

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

    static class ViewHolder extends RecyclerView.ViewHolder {
        MaterialButton btnTimeSlot;

        ViewHolder(View itemView) {
            super(itemView);
            btnTimeSlot = itemView.findViewById(R.id.btn_time_slot);
        }
    }
}
