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.Restaurant;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.List;

public class RestaurantAdapter extends RecyclerView.Adapter<RestaurantAdapter.ViewHolder> {
    private List<Restaurant> restaurants;
    private OnRestaurantClickListener listener;

    public interface OnRestaurantClickListener {
        void onRestaurantClick(Restaurant restaurant);
    }

    public RestaurantAdapter(List<Restaurant> restaurants, OnRestaurantClickListener listener) {
        this.restaurants = restaurants;
        this.listener = listener;
    }

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

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Restaurant restaurant = restaurants.get(position);
        holder.text1.setText(restaurant.getName());
        holder.text2.setText(restaurant.getCategory() + (restaurant.isAvailable() ? " - Disponível" : " - Indisponível"));
        
        if (restaurant.getLogoUrl() != null && !restaurant.getLogoUrl().isEmpty()) {
            com.bumptech.glide.Glide.with(holder.itemView.getContext())
                    .load(restaurant.getLogoUrl())
                    .circleCrop()
                    .into(holder.imgThumb);
        } else {
            holder.imgThumb.setImageResource(R.mipmap.ic_launcher);
        }
        
        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onRestaurantClick(restaurant);
            }
        });

        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        if (user != null && user.getEmail() != null && restaurant.getEmail() != null) {
            String encodedUserEmail = user.getEmail().replace(".", "_").replace("@", "_at_");
            String encodedRestEmail = restaurant.getEmail().replace(".", "_").replace("@", "_at_");
            DatabaseReference favRef = FirebaseDatabase.getInstance().getReference("users")
                    .child(encodedUserEmail).child("favorites").child(encodedRestEmail);

            favRef.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {
                    if (snapshot.exists()) {
                        holder.btnFavorite.setImageResource(android.R.drawable.btn_star_big_on);
                    } else {
                        holder.btnFavorite.setImageResource(android.R.drawable.btn_star_big_off);
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError error) { }
            });

            holder.btnFavorite.setOnClickListener(v -> {
                favRef.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {
                        if (snapshot.exists()) {
                            favRef.removeValue();
                        } else {
                            favRef.setValue(restaurant);
                        }
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError error) { }
                });
            });
        }
    }

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

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView text1, text2;
        ImageButton btnFavorite;
        android.widget.ImageView imgThumb;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            text1 = itemView.findViewById(R.id.txtRestaurantName);
            text2 = itemView.findViewById(R.id.txtRestaurantCategory);
            btnFavorite = itemView.findViewById(R.id.btnFavorite);
            imgThumb = itemView.findViewById(R.id.imgRestaurantThumb);
        }
    }
}
