package com.example.pap_teste;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
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 FeaturedRestaurantAdapter extends RecyclerView.Adapter<FeaturedRestaurantAdapter.ViewHolder> {
    private List<Restaurant> restaurants;
    private RestaurantAdapter.OnRestaurantClickListener listener;

    public FeaturedRestaurantAdapter(List<Restaurant> restaurants,
            RestaurantAdapter.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_featured, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Restaurant restaurant = restaurants.get(position);
        holder.txtName.setText(restaurant.getName());
        holder.txtCategory.setText("• " + restaurant.getCategory());

        if (holder.txtRating != null) {
            if (restaurant.getRatingAvg() != null && restaurant.getRatingAvg() > 0) {
                holder.txtRating
                        .setText(String.format(java.util.Locale.getDefault(), "%.1f", restaurant.getRatingAvg()));
            } else {
                holder.txtRating.setText("Novo");
            }
        }

        if (restaurant.getLogoUrl() != null && !restaurant.getLogoUrl().isEmpty()) {
            com.bumptech.glide.Glide.with(holder.itemView.getContext())
                    .load(restaurant.getLogoUrl())
                    .centerCrop()
                    .into(holder.imgCover);
        } else {
            holder.imgCover.setImageResource(R.mipmap.ic_launcher);
        }

        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onRestaurantClick(restaurant);
            }
        });

        if (holder.btnFavorite != null) {
            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("Clientes")
                        .child(encodedUserEmail).child("favorites").child(encodedRestEmail);

                // Read initial state
                favRef.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {
                        holder.btnFavorite.setTag(snapshot.exists());
                        if (snapshot.exists()) {
                            holder.btnFavorite.setImageResource(android.R.drawable.btn_star_big_on);
                            holder.btnFavorite.setColorFilter(androidx.core.content.ContextCompat
                                    .getColor(holder.itemView.getContext(), R.color.colorPrimary));
                        } else {
                            holder.btnFavorite.setImageResource(android.R.drawable.btn_star_big_off);
                            holder.btnFavorite.clearColorFilter();
                        }
                    }

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

                holder.btnFavorite.setOnClickListener(v -> {
                    // Optimistic UI update
                    boolean isFav = holder.btnFavorite.getTag() != null && (Boolean) holder.btnFavorite.getTag();
                    boolean newFavState = !isFav;
                    holder.btnFavorite.setTag(newFavState);

                    if (newFavState) {
                        holder.btnFavorite.setImageResource(android.R.drawable.btn_star_big_on);
                        holder.btnFavorite.setColorFilter(androidx.core.content.ContextCompat
                                .getColor(holder.itemView.getContext(), R.color.colorPrimary));
                        favRef.setValue(restaurant);
                        com.google.android.material.snackbar.Snackbar.make(v, "Adicionado aos Favoritos!",
                                com.google.android.material.snackbar.Snackbar.LENGTH_SHORT).show();
                    } else {
                        holder.btnFavorite.setImageResource(android.R.drawable.btn_star_big_off);
                        holder.btnFavorite.clearColorFilter();
                        favRef.removeValue();
                        com.google.android.material.snackbar.Snackbar.make(v, "Removido dos Favoritos.",
                                com.google.android.material.snackbar.Snackbar.LENGTH_SHORT).show();
                    }
                });
            }
        }
    }

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

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView txtName, txtCategory, txtRating;
        ImageView imgCover;
        android.widget.ImageButton btnFavorite;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            txtName = itemView.findViewById(R.id.txtFeaturedName);
            txtCategory = itemView.findViewById(R.id.txtFeaturedCategory);
            txtRating = itemView.findViewById(R.id.txtFeaturedRating);
            imgCover = itemView.findViewById(R.id.imgFeaturedCover);
            btnFavorite = itemView.findViewById(R.id.btnFavorite);
        }
    }
}
