package com.ar.arsketch.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.ar.arsketch.R;
import com.ar.arsketch.activity.CameraActivity;
import com.ar.arsketch.room.AppDatabase;
import com.ar.arsketch.room.ImageEntry;
import com.ar.arsketch.topon.AdManager;
import com.ar.arsketch.topon.onActionListener;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;

import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

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

    private List<ImageEntry> imageEntries;
    private final Context context;
    private Activity activity;
    private final Executor executor = Executors.newSingleThreadExecutor();

    public ImageAdapter(Context context, List<ImageEntry> imageEntries, Activity activity) {
        this.context = context;
        this.imageEntries = imageEntries;
        this.activity = activity;
    }

    public void updateData(List<ImageEntry> newFavoriteImages) {
        this.imageEntries = newFavoriteImages;
        notifyDataSetChanged();
    }

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

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        ImageEntry imageEntry = imageEntries.get(position);
        holder.bind(imageEntry);
    }

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

    class ViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        ImageView favoriteButton;

        ViewHolder(View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.image_view);
            favoriteButton = itemView.findViewById(R.id.btn_favorite);
        }

        void bind(ImageEntry favoriteImage) {
            String favoritePath = favoriteImage.getImagePath();

            loadImage(favoritePath);
            setFavoriteButton(favoriteImage);
            setClickListeners(favoriteImage);
        }

        private void loadImage(String favoritePath) {
            String imagePathToLoad = favoritePath.startsWith("/data/user/")
                    ? favoritePath
                    : "file:///android_asset/" + favoritePath;

            Glide.with(context)
                    .load(imagePathToLoad)
                    .transform(new RoundedCorners(20))
                    .error(R.mipmap.placeholder)
                    .placeholder(R.mipmap.placeholder)
                    .into(imageView);
        }

        private void setFavoriteButton(ImageEntry favoriteImage) {
            favoriteButton.setImageResource(favoriteImage.isFavoriteStatus()
                    ? R.drawable.like
                    : R.drawable.un_like);
        }

        private void setClickListeners(final ImageEntry favoriteImage) {
            imageView.setOnClickListener(v -> {
                AdManager.showTopOn(activity, new onActionListener() {
                    @Override
                    public void onAction() {
                        Intent intent = new Intent(context, CameraActivity.class);
                        intent.putExtra("imagePath", favoriteImage.getImagePath());
                        context.startActivity(intent);
                    }
                });
            });

            favoriteButton.setOnClickListener(v -> toggleFavorite(favoriteImage));
        }

        private void toggleFavorite(ImageEntry favoriteImage) {
            boolean newStatus = !favoriteImage.isFavoriteStatus();
            favoriteImage.setFavoriteStatus(newStatus);

            updateImageInDatabase(favoriteImage);
            notifyItemChanged(getAdapterPosition());
        }

        private void updateImageInDatabase(ImageEntry favoriteImage) {
            executor.execute(() -> {
                AppDatabase.getInstance(context)
                        .imageEntryDao()
                        .update(favoriteImage);
            });
        }
    }
}