package com.ar.artracestudio.adapter;

import android.app.Activity;
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.artracestudio.R;
import com.ar.artracestudio.activity.CameraActivity;
import com.ar.artracestudio.room.AppDatabase;
import com.ar.artracestudio.room.ImageEntry;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;

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

public class ImportAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final int VIEW_TYPE_HEADER = 0;
    private static final int VIEW_TYPE_ITEM = 1;

    private List<ImageEntry> imageEntries;
    private final Activity context;
    private final OnHeaderClickListener onHeaderClickListener;

    public ImportAdapter(List<ImageEntry> imageEntries, Activity context, OnHeaderClickListener onHeaderClickListener) {
        this.imageEntries = imageEntries;
        this.context = context;
        this.onHeaderClickListener = onHeaderClickListener;
    }

    public interface OnHeaderClickListener {
        void onHeaderClick();
    }

    @Override
    public int getItemViewType(int position) {
        return position == 0 ? VIEW_TYPE_HEADER : VIEW_TYPE_ITEM;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == VIEW_TYPE_HEADER) {
            // 加载特殊控件的布局
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_special_view, parent, false);
            return new HeaderViewHolder(view);
        } else {
            // 加载普通控件的布局
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_import, parent, false);
            return new ViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (getItemViewType(position) == VIEW_TYPE_HEADER) {
            HeaderViewHolder headerHolder = (HeaderViewHolder) holder;

            headerHolder.itemView.setOnClickListener(v -> {
                if (onHeaderClickListener != null) {
                    onHeaderClickListener.onHeaderClick();
                }
            });
        } else {
            ViewHolder itemHolder = (ViewHolder) holder;
            ImageEntry imageEntry = imageEntries.get(position - 1);

            ((ViewHolder) holder).bind(imageEntry);

            Glide.with(context)
                    .load(imageEntry.getImagePath())
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .transform(new RoundedCorners(20))
                    .into(itemHolder.imageView);

            itemHolder.imageView.setOnClickListener(v -> {
                Intent intent = new Intent(context, CameraActivity.class);
                intent.putExtra("imagePath", imageEntry.getImagePath()); // 传递图片路径
                context.startActivity(intent);
            });

        }
    }

    @Override
    public int getItemCount() {
        return imageEntries.size() + 1; // 加上 header 的项数
    }

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

    // Header ViewHolder 类（特殊控件）
    static class HeaderViewHolder extends RecyclerView.ViewHolder {
        public HeaderViewHolder(View view) {
            super(view);
            // 在这里可以初始化 Header 控件
        }
    }

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

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

        void bind(ImageEntry favoriteImage) {

            String favoritePath = favoriteImage.getImagePath();

            Glide.with(context)
                    .load(favoritePath)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .transform(new RoundedCorners(20))
                    .into(imageView);

            // 动态观察 'isFavorite' 状态，并更新按钮的图标
            favoriteButton.setImageResource(favoriteImage.isFavoriteStatus() ? R.drawable.like : R.drawable.unlike);

            // 设置收藏按钮的点击事件，切换收藏状态
            favoriteButton.setOnClickListener(v -> {
                boolean newStatus = !favoriteImage.isFavoriteStatus();  // 取反收藏状态
                favoriteImage.setFavoriteStatus(newStatus);  // 更新状态

                // 在后台线程中更新数据库
                Executors.newSingleThreadExecutor().execute(() -> {
                    AppDatabase.getInstance(context)
                            .imageEntryDao()
                            .update(favoriteImage);  // 更新数据库中的收藏状态
                });

                // 更新当前项的收藏按钮图标
                notifyItemChanged(getAdapterPosition());
            });

        }

    }
}
