package com.idle.wall;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.idle.wall.idleactivity.IdleWallActivity;
import com.idle.wall.idlebean.IdleData;
import com.idle.wall.idletool.Comutils;

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

public class RecentAdapter extends BaseAdapter {
    private Context context;
    private List<IdleWallpaper> wallpaperList = new ArrayList<>();
    private LayoutInflater inflater;
    private int itemWidth;
    private final int cornerRadius = 12;
    private RequestOptions glideOptions;
    private RequestOptions preloadOptions;
    private Handler mainHandler;

    public RecentAdapter(Context context, List<IdleWallpaper> wallpaperList) {
        this.context = context;
        this.wallpaperList = (wallpaperList != null) ? wallpaperList : new ArrayList<>();
        this.inflater = LayoutInflater.from(context);
        this.mainHandler = new Handler(Looper.getMainLooper());
        int screenWidth = context.getResources().getDisplayMetrics().widthPixels;
        int columnCount = 2;
        int spacing = (int) context.getResources().getDimension(R.dimen.grid_spacing);
        this.itemWidth = (screenWidth - (columnCount + 1) * spacing) / columnCount;

        // 优化后的Glide配置
        initGlideOptions();
    }

    private void initGlideOptions() {
        int radiusPx = dp2px(context, cornerRadius);
        RoundedCorners roundedCorners = new RoundedCorners(radiusPx);
        glideOptions = new RequestOptions()
                .format(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? DecodeFormat.PREFER_ARGB_8888 : DecodeFormat.PREFER_RGB_565)
                .override(itemWidth, itemWidth)
                .centerCrop()
                .transform(roundedCorners)
                .skipMemoryCache(false)
                .priority(Priority.HIGH)
                .timeout(5000)
                .placeholder(R.mipmap.im_placeholder)
                .error(R.mipmap.im_placeholder);
        preloadOptions = new RequestOptions()
                .override(itemWidth, itemWidth)
                .centerCrop()
                .transform(roundedCorners)
                .priority(Priority.NORMAL)
                .skipMemoryCache(false);
    }

    @Override
    public int getCount() {
        return wallpaperList.size();
    }

    @Override
    public Object getItem(int position) {
        return wallpaperList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.item_recent_wallpaper, parent, false);
            holder = new ViewHolder();
            holder.ivWallpaper = convertView.findViewById(R.id.iv_wallpaper);
            ViewGroup.LayoutParams params = holder.ivWallpaper.getLayoutParams();
            params.width = itemWidth;
            params.height = itemWidth;
            holder.ivWallpaper.setLayoutParams(params);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        IdleWallpaper wallpaper = wallpaperList.get(position);
        String imagePath = wallpaper.getImageUrl();

        // 优化后的图片加载逻辑
        loadImageOptimized(holder.ivWallpaper, imagePath);

        convertView.setOnClickListener(v -> {
            IdleData idleData = new IdleData();
            idleData.setImId(wallpaper.getId());
            idleData.setFullUrl(wallpaper.getImageUrl());
            idleData.setPreviewUrl400(wallpaper.getImageUrl());
            idleData.setDescription(wallpaper.getTitle() != null ? wallpaper.getTitle() : "");

            Intent intent = new Intent(context, IdleWallActivity.class);
            intent.putExtra(Comutils.key_info, idleData);
            context.startActivity(intent);
        });

        return convertView;
    }
    private void loadImageOptimized(ImageView imageView, String imageUrl) {
        if (imageUrl == null || imageUrl.isEmpty()) {
            Glide.with(context)
                    .load(R.mipmap.im_placeholder)
                    .into(imageView);
            return;
        }

        RequestBuilder<Bitmap> thumbnailRequest = Glide.with(context)
                .asBitmap()
                .load(imageUrl)
                .apply(RequestOptions.overrideOf(itemWidth / 4, itemWidth / 4)
                        .priority(Priority.IMMEDIATE));

        Glide.with(context)
                .asBitmap()
                .load(imageUrl)
                .apply(glideOptions)
                .thumbnail(thumbnailRequest)
                .into(imageView);
    }

    static class ViewHolder {
        ImageView ivWallpaper;
    }

    public void updateData(List<IdleWallpaper> newList) {
        this.wallpaperList = (newList != null) ? newList : new ArrayList<>();
        notifyDataSetChanged();

        mainHandler.postDelayed(() -> preloadImagesOptimized(5), 100);
    }
    private void preloadImagesOptimized(int count) {
        if (wallpaperList.isEmpty() || context == null) return;

        int preloadCount = Math.min(count, wallpaperList.size());

        for (int i = 0; i < preloadCount; i++) {
            String imageUrl = wallpaperList.get(i).getImageUrl();
            if (imageUrl == null || imageUrl.isEmpty()) continue;

            Glide.with(context)
                    .load(imageUrl)
                    .apply(preloadOptions)
                    .preload(itemWidth, itemWidth);
        }
    }

    // 原有dp转px，无修改
    private int dp2px(Context context, int dp) {
        float density = context.getResources().getDisplayMetrics().density;
        return (int) (dp * density + 0.5f);
    }

    public void release() {
        if (mainHandler != null) {
            mainHandler.removeCallbacksAndMessages(null);
        }
        this.context = null;
    }
}