package com.example.petstoremobile.adapters;

import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.petstoremobile.R;
import com.example.petstoremobile.api.PetApi;
import com.example.petstoremobile.databinding.ItemPetBinding;
import com.example.petstoremobile.dtos.PetDTO;
import com.example.petstoremobile.utils.BulkDeleteHandler;
import com.example.petstoremobile.utils.GlideUtils;
import com.example.petstoremobile.utils.SelectionHelper;

import java.util.List;

public class PetAdapter extends RecyclerView.Adapter<PetAdapter.PetViewHolder> implements BulkDeleteHandler.SelectableAdapter {

    private List<PetDTO> petList;
    private OnPetClickListener petClickListener;
    private String baseUrl;
    private String token;
    private final SelectionHelper selectionHelper;

    // Interface for pet click on recycler view
    public interface OnPetClickListener {
        void onPetClick(int position);
        void onSelectionChanged(int selectedCount);
    }

    //Constructor
    public PetAdapter(List<PetDTO> petList, OnPetClickListener petClickListener) {
        this.petList  = petList;
        this.petClickListener = petClickListener;
        this.selectionHelper = new SelectionHelper(new SelectionHelper.SelectionListener() {
            @Override
            public void onSelectionChanged(int count) {
                petClickListener.onSelectionChanged(count);
            }

            @Override
            public void onSelectionModeToggle(boolean selectionMode) {
                notifyDataSetChanged();
            }
        });
    }

    public void setBaseUrl(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    public void setToken(String token) {
        this.token = token;
    }

    @Override
    public List<String> getSelectedKeys() {
        return selectionHelper.getSelectedKeys();
    }

    @Override
    public void clearSelection() {
        selectionHelper.clearSelection();
    }

    // Get the controls of each row in recycler view
    public static class PetViewHolder extends RecyclerView.ViewHolder {
        private final ItemPetBinding binding;

        public PetViewHolder(@NonNull ItemPetBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }

    // Create a new row view
    @NonNull
    @Override
    public PetViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemPetBinding binding = ItemPetBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
        return new PetViewHolder(binding);
    }

    //populate the row with pet data
    @Override
    public void onBindViewHolder(@NonNull PetViewHolder holder, int position) {
        PetDTO pet = petList.get(position);
        ItemPetBinding binding = holder.binding;

        binding.tvPetName.setText(pet.getPetName());
        binding.tvPetSpeciesBreed.setText(pet.getPetSpecies() + " - " + pet.getPetBreed());
        binding.tvPetAge.setText("Age: " + pet.getPetAge() + " yr(s)");
        
        Double price = pet.getPetPrice();
        if (price != null) {
            binding.tvPetPrice.setText("$" + String.format("%.2f", price));
        } else {
            binding.tvPetPrice.setText("$0.00");
        }
        
        binding.tvPetStatus.setText(pet.getPetStatus());

        //Set the status color depending on availability. If available, green, If Pending, yellow, otherwise red
        if (pet.getPetStatus() != null) {
            switch (pet.getPetStatus()) {
                case "Available":
                    binding.tvPetStatus.setBackgroundColor(Color.parseColor("#4CAF50"));
                    break;
                case "Pending":
                    binding.tvPetStatus.setBackgroundColor(Color.parseColor("#FF9800"));
                    break;
                default:
                    binding.tvPetStatus.setBackgroundColor(Color.parseColor("#F44336"));
                    break;
            }
        } else {
            binding.tvPetStatus.setBackgroundColor(Color.parseColor("#9E9E9E"));
        }

        // Load pet image using Glide
        if (baseUrl != null) {
            String imageUrl = baseUrl + String.format(PetApi.PET_IMAGE_PATH, pet.getPetId());
            GlideUtils.loadImageWithTokenCircle(holder.itemView.getContext(), binding.ivPetProfile, imageUrl, token, R.drawable.placeholder);
        } else {
            binding.ivPetProfile.setImageResource(R.drawable.placeholder);
        }

        String key = String.valueOf(pet.getPetId());

        // Bulk delete selection mode
        if (selectionHelper.isInSelectionMode()) {
            binding.cbSelectPet.setVisibility(View.VISIBLE);
            binding.cbSelectPet.setChecked(selectionHelper.isSelected(key));
        } else {
            binding.cbSelectPet.setVisibility(View.GONE);
            binding.cbSelectPet.setChecked(false);
        }

        //when a row is clicked, open the detail view
        holder.itemView.setOnClickListener(v -> {
            if (selectionHelper.isInSelectionMode()) {
                selectionHelper.toggleSelection(key);
                notifyItemChanged(position);
            } else {
                petClickListener.onPetClick(position);
            }
        });

        holder.itemView.setOnLongClickListener(v -> {
            if (!selectionHelper.isInSelectionMode()) {
                selectionHelper.startSelection(key);
            }
            return true;
        });
    }

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