package com.house.wallpapers.myitem;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

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

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.house.wallpapers.App;
import com.house.wallpapers.adapter.OnItemclick;
import com.house.wallpapers.mybean.Data;
import com.house.wallpapers.mytool.Comutils;
import com.house.wallpapers.mytool.ObectManager;
import com.house.wallpapers.R;

import java.util.ArrayList;
import java.util.List;

import jp.wasabeef.glide.transformations.RoundedCornersTransformation;

public class ItemFavorite extends RecyclerView.Adapter<ItemFavorite.LikeVh> {

    private List<Data> dataInfo = new ArrayList<>();
    private Context myContext;
    private OnItemclick onItemClick;

    public void setInfoWallpaperListener(OnItemclick onItemClick) {
        this.onItemClick = onItemClick;
    }

    public ItemFavorite(Context myCon) {
        myContext = myCon;
    }

    // 优化：添加数据清空和批量添加方法（避免重复数据）
    public void setDataInfo(List<Data> dataInfo) {
        if (dataInfo != null) {
            this.dataInfo.clear();
            this.dataInfo.addAll(dataInfo);
            notifyDataSetChanged();
        }
    }

    @NonNull
    @Override
    public LikeVh onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(myContext).inflate(R.layout.item_favorite, parent, false);
        return new LikeVh(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull LikeVh holder, int position) {
        // 安全检查：避免数组越界（防止数据为空或位置异常）
        if (position < 0 || position >= dataInfo.size()) {
            return;
        }

        Data info = dataInfo.get(position);
        ImageView imageView = holder.getImageView();
        ImageView imFavorite = holder.getImFavorite();
        View spaceView = holder.getSpaceView();

        // 核心修复：添加空安全判断（解决空指针崩溃）
        if (spaceView != null) {
            // 最后一项显示底部间距，其他项隐藏
            spaceView.setVisibility(position == dataInfo.size() - 1 ? View.VISIBLE : View.GONE);
        }

        // 圆角变换（优化：避免每次绑定都创建新对象，可复用）
        MultiTransformation<Bitmap> multiTransformation = new MultiTransformation<>(
                new CenterCrop(),
                new RoundedCornersTransformation(Comutils.dp2Px(12), 0)
        );

        // Glide加载图片（优化：添加错误占位图，避免加载失败显示空白）
        Glide.with(myContext)
                .load(info.getPreviewUrl400())
                .placeholder(R.mipmap.im_placeholder)
                .error(R.mipmap.im_placeholder) // 新增：加载失败时显示占位图
                .transform(multiTransformation)
                .into(imageView);

        // 收藏按钮状态设置（添加空判断）
        if (imFavorite != null) {
            imFavorite.setSelected(true);
            imFavorite.setOnClickListener(v -> {
                imFavorite.setSelected(false);
                info.setLike(false);
                ObectManager.updateLike(info);
                // 安全获取位置（避免holder复用导致的位置错误）
                int adapterPosition = holder.getAdapterPosition();
                if (adapterPosition != RecyclerView.NO_POSITION) {
                    dataInfo.remove(adapterPosition);
                    notifyItemRemoved(adapterPosition);
                    // 修复：删除后刷新后续item的位置，避免布局错乱
                    notifyItemRangeChanged(adapterPosition, dataInfo.size());
                    Log.d(App.TAG, "----------notifyItemRemoved-adapterPosition=" + adapterPosition);
                }
            });
        }

        // item点击事件（添加空判断）
        if (holder.getLayout() != null) {
            holder.getLayout().setOnClickListener(v -> {
                if (onItemClick != null) {
                    onItemClick.onItemClickAction(info);
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        // 安全返回：避免dataInfo为null导致崩溃
        return dataInfo != null ? dataInfo.size() : 0;
    }

    public class LikeVh extends RecyclerView.ViewHolder {
        private ImageView imageView;
        private RelativeLayout layout;
        private ImageView imFavorite;
        private View spaceView;

        public LikeVh(@NonNull View itemView) {
            super(itemView);
            // 绑定控件（确保ID与item_like.xml完全一致）
            imageView = itemView.findViewById(R.id.wallpaper);
            layout = itemView.findViewById(R.id.layout);
            imFavorite = itemView.findViewById(R.id.image_favorite);
            spaceView = itemView.findViewById(R.id.space_view); // 关键：对应item布局中的底部间距控件
        }

        // getter方法（保持不变）
        public View getSpaceView() {
            return spaceView;
        }

        public ImageView getImFavorite() {
            return imFavorite;
        }

        public RelativeLayout getLayout() {
            return layout;
        }

        public ImageView getImageView() {
            return imageView;
        }
    }
}