package com.ar.artraceartpro.ui.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 android.widget.TextView;

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

import com.ar.artraceartpro.topon.AdManager;
import com.ar.artraceartpro.topon.onActionListener;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.ar.artraceartpro.R;
import com.ar.artraceartpro.data.local.database.AppDatabase;
import com.ar.artraceartpro.data.local.entity.ImageData;
import com.ar.artraceartpro.ui.activity.CameraActivity;
import com.ar.artraceartpro.ui.activity.CategoryActivity;

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

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

    private List<ImageData> imageEntries;
    private final Context context;
    private final Activity activity;
    private final int type;
    private final List<String> categories;

    public ImageRecyclerViewAdapter(List<ImageData> imageEntries, Context context, Activity activity, int type, List<String> categories) {
        this.context = context;
        this.imageEntries = imageEntries;
        this.activity = activity;
        this.type = type;
        this.categories = categories;
    }

    public void updateData(List<ImageData> 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) {
        ImageData imageData = imageEntries.get(position);
        String name = "";
        if (type == 0) {
            name = categories.get(position);
        } else {
            name = "";
        }
        holder.bind(imageData, name);
    }

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

    public class ViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        ImageView like;
        TextView text;

        ViewHolder(View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.image);
            like = itemView.findViewById(R.id.like);
            text = itemView.findViewById(R.id.title);
        }

        void bind(ImageData imageData, String name) {
            String favoritePath = imageData.getImagePath();

            if (type == 0) {
                text.setVisibility(View.VISIBLE);
                setItemText(name);
            }

            loadImage(favoritePath);
            setLike(imageData);
            setClickListeners(imageData, name);
        }

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

            Glide.with(context)
                    .load(imagePathToLoad)
                    .transform(new RoundedCorners(32))
                    .into(imageView);
        }

        private void setItemText(String name) {
            String title = name.substring(4);
            text.setText(title);
        }

        private void setLike(ImageData favoriteImage) {
            like.setImageResource(favoriteImage.isFavorite()
                    ? R.drawable.like
                    : R.drawable.dislike);
        }

        private void setClickListeners(final ImageData imageData, String name) {
            imageView.setOnClickListener(v -> {
                AdManager.showTopOn(activity, new onActionListener() {
                    @Override
                    public void onAction() {
                        Intent intent;
                        if (type == 0) {
                            intent = new Intent(context, CategoryActivity.class);
                            intent.putExtra("name", name);
                        } else {
                            intent = new Intent(context, CameraActivity.class);
                            intent.putExtra("imagePath", imageData.getImagePath());
                        }
                        context.startActivity(intent);
                    }
                });
            });

            like.setOnClickListener(v -> toggleFavorite(imageData));
        }

        private void toggleFavorite(ImageData favoriteImage) {
            boolean newStatus = !favoriteImage.isFavorite();
            favoriteImage.setFavorite(newStatus);

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

        private void updateImageInDatabase(ImageData favoriteImage) {
            Executors.newSingleThreadExecutor().execute(() -> {
                AppDatabase.getInstance(context)
                        .imageDataDao()
                        .update(favoriteImage);
            });
        }
    }
}