package com.idle.wall.idleitem;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ImageView;

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

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.signature.ObjectKey;
import com.idle.wall.R;
import com.idle.wall.IdleApp;
import com.idle.wall.databinding.ItemIdleMainBinding;
import com.idle.wall.idleadapter.OnItemclick;
import com.idle.wall.idlebean.IdleData;
import com.idle.wall.idletool.Comutils;
import com.idle.wall.idletool.JsonData;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ItemIdleMain extends ListAdapter<String, ItemIdleMain.MainViewHolder> {
    private static final ExecutorService JSON_PARSE_POOL = Executors.newSingleThreadExecutor();
    private static RequestOptions IMAGE_OPTIONS;
    private final List<IdleData> categoryFirstDataCache = new java.util.ArrayList<>();
    private OnItemclick listener;
    private final Context appContext;

    private static final DiffUtil.ItemCallback<String> DIFF_CALLBACK = new DiffUtil.ItemCallback<String>() {
        @Override
        public boolean areItemsTheSame(@NonNull String oldItem, @NonNull String newItem) {
            return oldItem.equals(newItem);
        }

        @Override
        public boolean areContentsTheSame(@NonNull String oldItem, @NonNull String newItem) {
            return oldItem.equals(newItem);
        }
    };

    public ItemIdleMain() {
        super(DIFF_CALLBACK);
        this.appContext = IdleApp.mAppContext;
        initImageOptions();
    }

    private void initImageOptions() {
        if (IMAGE_OPTIONS == null && appContext != null) {
            int cornerDp = 12;
            int cornerPx = Comutils.dp2px(appContext, cornerDp);
            IMAGE_OPTIONS = new RequestOptions()
                    .transform(new CenterCrop(), new RoundedCorners(cornerPx))
                    .placeholder(R.mipmap.im_placeholder)
                    .error(R.mipmap.im_placeholder)
                    .diskCacheStrategy(com.bumptech.glide.load.engine.DiskCacheStrategy.ALL)
                    .skipMemoryCache(false)
                    .timeout(10000);
        }
    }

    public void submitCategoryData(List<String> newCategoryNames) {
        if (newCategoryNames == null || newCategoryNames.isEmpty()) {
            submitList(null);
            categoryFirstDataCache.clear();
            return;
        }

        submitList(newCategoryNames);
        JSON_PARSE_POOL.execute(() -> {
            parseCategoryDataAsync(newCategoryNames);
        });
    }

    private void parseCategoryDataAsync(List<String> newCategoryNames) {
        if (appContext == null) return;

        synchronized (categoryFirstDataCache) {
            categoryFirstDataCache.clear();
        }

        for (String categoryName : newCategoryNames) {
            IdleData firstData = null;
            try {
                String jsonFileName = categoryName + ".json";
                InputStream open = appContext.getAssets().open(jsonFileName);
                String jsonStr = Comutils.getCovertStr(open);
                if (!jsonStr.isEmpty()) {
                    List<IdleData> data = JsonData.INSTANCE.getData(jsonStr, categoryName);
                    if (!data.isEmpty()) {
                        Collections.shuffle(data);
                        firstData = data.get(0);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                firstData = null;
            }
            synchronized (categoryFirstDataCache) {
                categoryFirstDataCache.add(firstData);
            }
        }

        new Handler(Looper.getMainLooper()).post(() -> {
            notifyItemRangeChanged(0, getItemCount());
        });
    }

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

    @NonNull
    @Override
    public MainViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemIdleMainBinding binding = ItemIdleMainBinding.inflate(
                LayoutInflater.from(parent.getContext()),
                parent,
                false
        );
        binding.ivCategory.setScaleType(ImageView.ScaleType.CENTER_CROP);
        binding.ivCategory.setAdjustViewBounds(true);
        return new MainViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull MainViewHolder holder, int position) {
        String categoryName = getItem(position);
        if (categoryName == null) return;

        holder.binding.tvCategoryName.setText(categoryName);

        // 修复核心：创建final局部变量，让lambda可以引用
        final IdleData finalFirstData;
        synchronized (categoryFirstDataCache) {
            if (position < categoryFirstDataCache.size()) {
                finalFirstData = categoryFirstDataCache.get(position);
            } else {
                finalFirstData = null;
            }
        }

        if (finalFirstData != null && finalFirstData.getPreviewUrl400() != null) {
            String imageUrl = finalFirstData.getPreviewUrl400();
            Glide.with(holder.itemView.getContext())
                    .load(imageUrl)
                    .apply(IMAGE_OPTIONS)
                    .signature(new ObjectKey(imageUrl + System.currentTimeMillis() / 3600000))
                    .into(holder.binding.ivCategory);
        } else {
            holder.binding.ivCategory.setImageResource(R.mipmap.im_placeholder);
        }

        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                IdleData myData = new IdleData();
                myData.setCategoryName(categoryName);
                myData.setImId(categoryName + "_" + position);
                // 引用final变量，不再报错
                if (finalFirstData != null) {
                    myData.setPreviewUrl400(finalFirstData.getPreviewUrl400());
                }
                listener.onItemClickAction(myData);
            }
        });
    }

    static class MainViewHolder extends RecyclerView.ViewHolder {
        final ItemIdleMainBinding binding;

        public MainViewHolder(@NonNull ItemIdleMainBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }

    public void release() {
        JSON_PARSE_POOL.shutdown();
        categoryFirstDataCache.clear();
        listener = null;
    }
}