package com.idle.wall.idleitem;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.recyclerview.widget.RecyclerView;
import com.idle.wall.R;
import com.idle.wall.idlebean.IdleData;
import com.idle.wall.idleadapter.OnItemclick;
import com.idle.wall.idletool.Comutils;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ItemIdleList extends RecyclerView.Adapter<ItemIdleList.ViewHolder> {
    private Context mContext;
    private List<IdleData> mDataList;
    private OnItemclick mListener;
    private OkHttpClient okHttpClient = new OkHttpClient();
    private Handler mainHandler = new Handler(Looper.getMainLooper());
    private int placeholderResId = R.mipmap.im_placeholder;

    public ItemIdleList(Context context, int itemHeight, boolean isHorizontal) {
        this.mContext = context;
    }

    public void setDataInfo(List<IdleData> dataList) {
        this.mDataList = dataList;
        notifyDataSetChanged();
    }

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

    public static class SpaceItemDecoration extends RecyclerView.ItemDecoration {
        private int spacing;

        public SpaceItemDecoration(int spacing) {
            this.spacing = spacing;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            outRect.left = spacing / 2;
            outRect.right = spacing / 2;
            outRect.bottom = spacing / 2;
            if (parent.getChildLayoutPosition(view) < 2) {
                outRect.top = spacing;
            } else {
                outRect.top = spacing / 2;
            }
        }
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_idle_list, parent, false);
        ViewGroup.LayoutParams params = view.getLayoutParams();
        int spacing = Comutils.dp2Px(10);
        int itemWidth = (parent.getWidth() - spacing) / 2;
        params.width = itemWidth;
        params.height = itemWidth;
        view.setLayoutParams(params);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        if (holder == null || position < 0 || position >= getItemCount()) {
            return;
        }

        IdleData idleData = mDataList.get(position);
        if (idleData == null) {
            if (holder.ivWallpaper != null) {
                holder.ivWallpaper.setImageResource(placeholderResId);
            }
            return;
        }

        if (holder.ivWallpaper == null) {
            return;
        }
        holder.ivWallpaper.setImageResource(placeholderResId);

        String realImageUrl = idleData.getPreviewUrl400();
        if (realImageUrl != null && !realImageUrl.isEmpty() && realImageUrl.startsWith("http")) {
            Request request = new Request.Builder().url(realImageUrl).build();
            Call call = okHttpClient.newCall(request);

            holder.currentCall = call;

            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    mainHandler.post(() -> {
                        if (holder.ivWallpaper != null && !call.isCanceled()) {
                            holder.ivWallpaper.setImageResource(placeholderResId);
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (call.isCanceled() || !response.isSuccessful() || response.body() == null) {
                        response.close();
                        mainHandler.post(() -> {
                            if (holder.ivWallpaper != null) {
                                holder.ivWallpaper.setImageResource(placeholderResId);
                            }
                        });
                        return;
                    }

                    InputStream inputStream = null;
                    try {
                        inputStream = response.body().byteStream();
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inSampleSize = 2;
                        options.inPreferredConfig = Bitmap.Config.RGB_565;
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options);

                        mainHandler.post(() -> {
                            if (holder.ivWallpaper != null && !call.isCanceled()) {
                                if (bitmap != null) {
                                    holder.ivWallpaper.setImageBitmap(bitmap);
                                } else {
                                    // Bitmap解码失败时显示占位图
                                    holder.ivWallpaper.setImageResource(placeholderResId);
                                }
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                        mainHandler.post(() -> {
                            if (holder.ivWallpaper != null) {
                                holder.ivWallpaper.setImageResource(placeholderResId);
                            }
                        });
                    } finally {
                        if (inputStream != null) {
                            inputStream.close();
                        }
                        response.close();
                    }
                }
            });
        } else {
            // URL为空/非法时显示统一占位图（替换系统默认图标）
            holder.ivWallpaper.setImageResource(placeholderResId);
        }

        holder.itemView.setOnClickListener(v -> {
            if (mListener != null) {
                mListener.onItemClickAction(idleData);
            }
        });
    }

    @Override
    public void onViewRecycled(ViewHolder holder) {
        super.onViewRecycled(holder);
        if (holder.currentCall != null) {
            holder.currentCall.cancel();
            holder.currentCall = null;
        }
        if (holder.ivWallpaper != null) {
            // 回收时重置为占位图，避免复用Item显示旧图片
            holder.ivWallpaper.setImageResource(placeholderResId);
            // 释放Bitmap，优化内存
            holder.ivWallpaper.setImageBitmap(null);
        }
    }

    @Override
    public int getItemCount() {
        return mDataList == null ? 0 : mDataList.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView ivWallpaper;
        Call currentCall;

        public ViewHolder(View itemView) {
            super(itemView);
            ivWallpaper = itemView.findViewById(R.id.iv_wallpaper);
        }
    }
}