package com.borjabolufer.elevate.adapters;

import android.os.Bundle;
import android.util.Log;
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.fragment.app.Fragment;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.RecyclerView;
import com.borjabolufer.elevate.R;
import com.borjabolufer.elevate.model.Comida;
import com.borjabolufer.elevate.model.ValorNutricional;
import com.borjabolufer.elevate.ui.fragments.DietFragment;

import java.util.List;

public class ComidaAdapter extends RecyclerView.Adapter<ComidaAdapter.ComidaViewHolder> {

    private static final String TAG = "ComidaAdapter";
    private List<DietFragment.ComidaItem> comidas;
    private Fragment parentFragment;

    public ComidaAdapter(List<DietFragment.ComidaItem> comidas) {
        this.comidas = comidas;
    }

    public ComidaAdapter(List<DietFragment.ComidaItem> comidas, Fragment parentFragment) {
        this.comidas = comidas;
        this.parentFragment = parentFragment;
    }

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

    @Override
    public void onBindViewHolder(@NonNull ComidaViewHolder holder, int position) {
        DietFragment.ComidaItem item = comidas.get(position);
        holder.bind(item, parentFragment);
    }

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

    static class ComidaViewHolder extends RecyclerView.ViewHolder {
        TextView textNombreComida, textDescripcion, textCalorias, textProteinas, textCarbos, textGrasas;
        ImageView iconComida;

        ComidaViewHolder(@NonNull View itemView) {
            super(itemView);
            textNombreComida = itemView.findViewById(R.id.text_nombre_comida);
            textDescripcion = itemView.findViewById(R.id.text_descripcion_comida);
            textCalorias = itemView.findViewById(R.id.text_calorias_comida);
            textProteinas = itemView.findViewById(R.id.text_proteinas_comida);
            textCarbos = itemView.findViewById(R.id.text_carbos_comida);
            textGrasas = itemView.findViewById(R.id.text_grasas_comida);
            iconComida = itemView.findViewById(R.id.icon_comida);
        }

        void bind(DietFragment.ComidaItem item, Fragment parentFragment) {
            Comida comida = item.getComida();

            textNombreComida.setText(item.getNombre());
            textDescripcion.setText(comida.getNombre());

            ValorNutricional vn = comida.getValor_nutricional();
            if (vn != null) {
                textCalorias.setText(vn.getCalorías() + " kcal");
                textProteinas.setText(vn.getProteínas() + "g");
                textCarbos.setText(vn.getCarbohidratos() + "g");
                textGrasas.setText(vn.getGrasas() + "g");
            } else {
                textCalorias.setText("0 kcal");
                textProteinas.setText("0g");
                textCarbos.setText("0g");
                textGrasas.setText("0g");
            }

            int iconResource;
            int tintColor;

            switch (item.getTipo()) {
                case "desayuno":
                    iconResource = R.drawable.ic_desayuno;
                    tintColor = R.color.warning;
                    break;
                case "comida":
                    iconResource = R.drawable.ic_comida;
                    tintColor = R.color.primary;
                    break;
                case "cena":
                    iconResource = R.drawable.ic_cena;
                    tintColor = R.color.info;
                    break;
                case "snacks":
                    iconResource = R.drawable.ic_snack;
                    tintColor = R.color.success;
                    break;
                default:
                    iconResource = R.drawable.ic_restaurante;
                    tintColor = R.color.info;
                    break;
            }

            iconComida.setImageResource(iconResource);
            iconComida.setColorFilter(itemView.getContext().getColor(tintColor));

            itemView.setOnClickListener(v -> {
                try {
                    Bundle args = new Bundle();
                    args.putSerializable("comida", comida);
                    args.putString("tipo_comida", item.getTipo());

                    Log.d(TAG, "Navegando al detalle de comida: " + comida.getNombre());

                    Navigation.findNavController(v).navigate(R.id.nav_detalle_comida, args);

                } catch (IllegalArgumentException e) {
                    Log.e(TAG, "Error de navegación - ID no encontrado en navigation.xml: " + e.getMessage());
                    if (itemView.getContext() instanceof android.app.Activity) {
                        ((android.app.Activity) itemView.getContext()).runOnUiThread(() -> {
                            android.widget.Toast.makeText(itemView.getContext(),
                                    "Error: Destino de navegación no configurado",
                                    android.widget.Toast.LENGTH_SHORT).show();
                        });
                    }
                } catch (Exception e) {
                    Log.e(TAG, "Error general de navegación: " + e.getMessage());
                    if (itemView.getContext() instanceof android.app.Activity) {
                        ((android.app.Activity) itemView.getContext()).runOnUiThread(() -> {
                            android.widget.Toast.makeText(itemView.getContext(),
                                    "Error al navegar al detalle",
                                    android.widget.Toast.LENGTH_SHORT).show();
                        });
                    }
                }
            });

            itemView.setClickable(true);
            itemView.setFocusable(true);
        }
    }
}