package com.snap.wall.myitem;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
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.snap.wall.App;
import com.snap.wall.adapter.OnItemclick;
import com.snap.wall.bean.Information;
import com.snap.wall.mytool.Comutils;
import com.snap.wall.mytool.ObectManager;
import com.snap.wall.R;

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

import jp.wasabeef.glide.transformations.RoundedCornersTransformation;

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

    // 全局复用的图片变换对象（圆角+居中裁剪）
    private static final MultiTransformation<Bitmap> TRANSFORMATION = new MultiTransformation<>(
            new CenterCrop(),
            new RoundedCornersTransformation(Comutils.dp2Px(12), 0)
    );

    private List<Information> mWallpaperList = new ArrayList<>();
    private Context mContext;
    private OnItemclick mOnItemClick;
    private int mItemWidth; // 新增：保存Item的1:1宽度

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

    public ItemPrefer(Context context) {
        mContext = context;
        setHasStableIds(true); // 开启稳定ID，避免滑动闪烁
        // 初始化Item宽度：屏幕宽度/2 - 间距（适配2列GridLayout）
        initItemWidth();
    }

    // 新增：计算1:1的Item宽度（核心）
    private void initItemWidth() {
        if (mContext == null) return;
        WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        int screenWidth = dm.widthPixels;
        // 减去RecyclerView的ItemDecoration间距（15dp左右，根据你的实际间距调整）
        int spacing = Comutils.dp2Px(30); // 左右各15dp，适配Itemhelper(10,10,15)
        mItemWidth = (screenWidth - spacing) / 2; // 2列平分，保证1:1
    }

    public void setDataInfo(List<Information> dataInfo) {
        if (dataInfo != null) {
            this.mWallpaperList.clear();
            this.mWallpaperList.addAll(dataInfo);
            notifyDataSetChanged();
        }
    }

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

    @Override
    public void onBindViewHolder(@NonNull LikeVh holder, int position) {
        if (position < 0 || position >= mWallpaperList.size()) {
            return;
        }

        Information info = mWallpaperList.get(position);

        // 处理底部间距View
        if (holder.spaceView != null) {
            holder.spaceView.setVisibility(position == mWallpaperList.size() - 1 ? View.VISIBLE : View.GONE);
        }

        // 核心修改：强制设置Item布局为1:1正方形
        if (holder.layout != null && mItemWidth > 0) {
            ViewGroup.LayoutParams params = holder.layout.getLayoutParams();
            params.width = mItemWidth;
            params.height = mItemWidth; // 高度=宽度，实现1:1
            holder.layout.setLayoutParams(params);
        }

        // 初始化收藏按钮状态（读取真实数据状态）
        if (holder.ivFavorite != null) {
            holder.ivFavorite.setSelected(info.isLike());
            holder.ivFavorite.setOnClickListener(v -> {
                boolean newState = !holder.ivFavorite.isSelected();
                holder.ivFavorite.setSelected(newState);
                info.setLike(newState);
                ObectManager.updateLike(info);

                int adapterPosition = holder.getAdapterPosition();
                if (adapterPosition != RecyclerView.NO_POSITION) {
                    mWallpaperList.remove(adapterPosition);
                    notifyItemRemoved(adapterPosition);
                    // 计算需要更新的item数量，避免索引越界
                    int newSize = mWallpaperList.size();
                    if (adapterPosition < newSize) {
                        notifyItemRangeChanged(adapterPosition, newSize - adapterPosition);
                    }
                    Log.d(App.TAG, "----------notifyItemRemoved-adapterPosition=" + adapterPosition);
                }
            });
        }

        // 加载图片（处理空URL + 避免内存泄漏 + 圆角1:1）
        String imgUrl = info.getPreviewUrl400();
        if (imgUrl == null || imgUrl.isEmpty()) {
            holder.ivWallpaper.setImageResource(R.mipmap.im_placeholder);
        } else {
            Glide.with(holder.ivWallpaper) // 使用View上下文，绑定生命周期
                    .load(imgUrl)
                    .placeholder(R.mipmap.im_placeholder)
                    .error(R.mipmap.im_placeholder)
                    .transform(TRANSFORMATION) // 圆角+居中裁剪，适配1:1
                    .dontAnimate() // 关闭动画，避免滑动闪烁
                    .into(holder.ivWallpaper);
        }

        // 整个Item的点击事件
        if (holder.layout != null) {
            holder.layout.setOnClickListener(v -> {
                if (mOnItemClick != null) {
                    mOnItemClick.onItemClickAction(info);
                }
            });
        }
    }

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

    // 重写getItemId，提供稳定ID
    @Override
    public long getItemId(int position) {
        // 替换为Information的唯一标识字段（比如id）
        return mWallpaperList.get(position).getId();
    }

    public class LikeVh extends RecyclerView.ViewHolder {
        ImageView ivWallpaper;
        RelativeLayout layout;
        ImageView ivFavorite;
        View spaceView;

        public LikeVh(@NonNull View itemView) {
            super(itemView);
            ivWallpaper = itemView.findViewById(R.id.wallpaper);
            layout = itemView.findViewById(R.id.layout);
            ivFavorite = itemView.findViewById(R.id.image_favorite);
            spaceView = itemView.findViewById(R.id.space_view);
        }
    }
}