package com.idle.wall.idleitem;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.DisplayMetrics;
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.idle.wall.idleadapter.OnItemclick;
import com.idle.wall.idlebean.IdleData;
import com.idle.wall.idletool.Comutils;
import com.idle.wall.idletool.ObectManager;
import com.idle.wall.R;

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

import jp.wasabeef.glide.transformations.RoundedCornersTransformation;

public class ItemIdleLike extends RecyclerView.Adapter<ItemIdleLike.LikeVh> {
    private static final MultiTransformation<Bitmap> TRANSFORMATION = new MultiTransformation<>(
            new CenterCrop(),
            new RoundedCornersTransformation(Comutils.dp2Px(12), 0)
    );

    private List<IdleData> mWallpaperList = new ArrayList<>();
    private Context mContext;
    private OnItemclick mOnItemClick;
    private int mItemWidth;

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

    public ItemIdleLike(Context context) {
        mContext = context;
        setHasStableIds(true); // 开启稳定ID，避免滑动闪烁
        // 初始化Item宽度：屏幕宽度/2 - 间距（适配2列GridLayout）
        initItemWidth();
    }
    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;
        int spacing = Comutils.dp2Px(30);
        mItemWidth = (screenWidth - spacing) / 2;
    }

    public void setDataInfo(List<IdleData> 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_idle_like, parent, false);
        return new LikeVh(itemView);
    }

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

        IdleData info = mWallpaperList.get(position);

        if (holder.spaceView != null) {
            holder.spaceView.setVisibility(position == mWallpaperList.size() - 1 ? View.VISIBLE : View.GONE);
        }
        if (holder.layout != null && mItemWidth > 0) {
            ViewGroup.LayoutParams params = holder.layout.getLayoutParams();
            params.width = mItemWidth;
            params.height = mItemWidth;
            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);
                    }
                }
            });
        }

        String imgUrl = info.getPreviewUrl400();
        if (imgUrl == null || imgUrl.isEmpty()) {
            holder.ivWallpaper.setImageResource(R.mipmap.im_placeholder);
        } else {
            Glide.with(holder.ivWallpaper)
                    .load(imgUrl)
                    .placeholder(R.mipmap.im_placeholder)
                    .error(R.mipmap.im_placeholder)
                    .transform(TRANSFORMATION)
                    .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);
        }
    }
}