package com.ardraw.ardrawinggallery.adapter;

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.ardraw.ardrawinggallery.R;
import com.ardraw.ardrawinggallery.activity.PaintActivity;
import com.ardraw.ardrawinggallery.activity.SubActivity;
import com.ardraw.ardrawinggallery.room.AppDatabase;
import com.ardraw.ardrawinggallery.room.ArData;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;

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

public class GalleryAdapter extends RecyclerView.Adapter<GalleryAdapter.ViewHolder> {
    private List<ArData> arDataList;
    private final Context context;
    private final int type;

    public GalleryAdapter(List<ArData> arDataList, Context context, int type) {
        this.context = context;
        this.arDataList = arDataList;
        this.type = type;
    }

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

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

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        ArData arData = arDataList.get(position);
        String name;
        if (type == 0) {
            String[] parts = arData.getImagePath().split("/");
            name = parts[0].split("_")[1];
        } else {
            name = "";
        }
        holder.bind(arData, name, type);
    }

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

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

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

        void bind(ArData arData, String name, int type) {
            if (type == 0) {
                displayTitle(name);
                displayLike();
            }

            loadImage(arData.getImagePath());
            updateLikeStatus(arData);
            setupClickListeners(arData,type);
        }

        private void loadImage(String imagePath) {
            String imagePathToLoad = formatImagePath(imagePath);

            Glide.with(imageView.getContext())
                    .load(imagePathToLoad)
                    .placeholder(R.mipmap.placeholder)
                    .transform(new RoundedCorners(32))
                    .into(imageView);
        }

        private String formatImagePath(String imagePath) {
            if (imagePath.startsWith("/data/user/")) {
                return imagePath;
            } else {
                return "file:///android_asset/" + imagePath;
            }
        }

        private void displayTitle(String name) {
            text.setVisibility(View.VISIBLE);
            text.setText(name);
        }

        private void displayLike() {
            like.setVisibility(View.GONE);
        }

        private void updateLikeStatus(ArData arData) {
            like.setImageResource(arData.isFavorite() ? R.drawable.like : R.drawable.un_like);
        }

        private void setupClickListeners(ArData arData,int type) {
            imageView.setOnClickListener(v -> onImageClick(arData, type));
            like.setOnClickListener(v -> toggleFavorite(arData));
        }

        private void onImageClick(ArData arData,int type) {
            Intent intent = (type == 0)
                    ? new Intent(imageView.getContext(), SubActivity.class).putExtra("Path", arData.getImagePath())
                    : new Intent(imageView.getContext(), PaintActivity.class).putExtra("WallpaperPath", arData.getImagePath());

            imageView.getContext().startActivity(intent);
        }

        private void toggleFavorite(ArData arData) {
            boolean newFavoriteStatus = !arData.isFavorite();
            arData.setFavorite(newFavoriteStatus);
            updateDatabase(arData);
            notifyItemChanged(getAdapterPosition());
        }

        private void updateDatabase(ArData arData) {
            Executors.newSingleThreadExecutor().submit(() -> {
                AppDatabase.getInstance(imageView.getContext()).arDataDao().update(arData);
            });
        }
    }
}