package com.app.paintingstool.myadapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

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

import com.app.paintingstool.R;
import com.app.paintingstool.databinding.ImageItemBinding;
import com.app.paintingstool.myact.CarmelActivity;
import com.app.paintingstool.mydao.AppDatabase;
import com.app.paintingstool.mydao.FavoriteImage;
import com.app.paintingstool.myinter.OnClickListener;
import com.app.paintingstool.myuntils.Keys;
import com.bumptech.glide.Glide;

import java.util.List;

public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ViewHolder> {
    private final List<String> dir;
    private final Context context;
    private RecyclerView recyclerView;
    private OnClickListener onClickListener;
    private final Activity activity;


    public ImageAdapter(List<String> dir, Context context,Activity activity) {
        this.dir = dir;
        this.context = context;
        this.activity=activity;

    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ImageItemBinding binding = ImageItemBinding.inflate(LayoutInflater.from(context), parent, false);
        return new ViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, @SuppressLint("RecyclerView") int position) {
        String name = dir.get(position);
        AppDatabase database = AppDatabase.getInstance(context);
        initView(holder, database, name);
        if (position < 10) {
            loadImage(position);
        } else {
            holder.binding.image.setImageResource(R.drawable.ic_launcher_foreground);
        }
        holder.binding.loved.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addOrCancel();
            }

            private void addOrCancel() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        FavoriteImage image = database.favoriteImageDao().findByUrl(name);
                        if (image != null) {
                            database.favoriteImageDao().delete(image);
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    holder.binding.loved.setImageResource(R.mipmap.icon_loved);
                                    Toast.makeText(context, "Cancel successfully", Toast.LENGTH_SHORT).show();
                                }
                            });
                        } else {
                            database.favoriteImageDao().insert(new FavoriteImage(name));
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    holder.binding.loved.setImageResource(R.mipmap.icon_fav);
                                    Toast.makeText(context, "Added successfully", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }
                }).start();
            }
        });
        holder.binding.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, CarmelActivity.class);
                intent.putExtra("nameCa", name);
                context.startActivity(intent);
            }
        });
    }

    private void initView(@NonNull ViewHolder holder, AppDatabase database, String name) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                FavoriteImage image = database.favoriteImageDao().findByUrl(name);
                if (image != null) {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            holder.binding.loved.setImageResource(R.mipmap.icon_fav);
                        }
                    });
                } else {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            holder.binding.loved.setImageResource(R.mipmap.icon_loved);
                        }
                    });
                }
            }
        }).start();
    }

    @Override
    public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        this.recyclerView = recyclerView; // 保存 RecyclerView 实例
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    loadVisibleImages();
                }
            }
        });
        recyclerView.post(new Runnable() {
            @Override
            public void run() {
                loadVisibleImages();
            }
        });
    }

    private void loadVisibleImages() {
        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        if (layoutManager != null) {
            int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
            int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
            for (int i = firstVisibleItemPosition - 5; i <= lastVisibleItemPosition + 5; i++) {
                if (i >= 0 && i < getItemCount()) {
                    loadImage(i);
                }
            }
        }
    }

    private void loadImage(int position) {
        ViewHolder viewHolder = (ViewHolder) recyclerView.findViewHolderForAdapterPosition(position);
        if (viewHolder != null) {
            String name = dir.get(position);
            Bitmap bitmap = Keys.loadImageFromAssets(context, name);
            viewHolder.binding.image.setImageBitmap(bitmap);
        }
    }

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

    @Override
    public void onViewRecycled(@NonNull ViewHolder holder) {
        super.onViewRecycled(holder);
        Glide.with(context).clear(holder.binding.image);
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        ImageItemBinding binding;

        public ViewHolder(ImageItemBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }
}