package com.gallery.free.wallpaper

import android.annotation.SuppressLint
import android.graphics.drawable.Drawable
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.target.Target


class WpPagerAdapter(
    private val wallpaperItems: List<WpItem>,
    private val loadListener: OnImageLoadListener? = null  // 添加加载监听器
) : RecyclerView.Adapter<WpPagerAdapter.ViewHolder>() {

    // 添加加载监听接口
    interface OnImageLoadListener {
        fun onImageLoadSuccess(position: Int)
        fun onImageLoadFailed(position: Int, error: Throwable)
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val imageView: ImageView = itemView.findViewById(R.id.pager_image_view)
        val loadingProgress: ImageView = itemView.findViewById(R.id.loading_progress)

        // 添加标识，防止错乱的UI更新
        var currentPosition: Int = -1
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_wp_pager, parent, false)
        return ViewHolder(view)
    }

    @SuppressLint("RecyclerView")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val wallpaperItem = wallpaperItems[position]

        Log.d("WallpaperPagerAdapter", "onBindViewHolder position=$position")

        // 设置当前position标识
        holder.currentPosition = position

        // 1. 立即显示loading
        holder.loadingProgress.visibility = View.VISIBLE
        holder.loadingProgress.bringToFront()

        // 2. 立即显示smallUrl（使用单独的Target）
        val smallUrlTarget = object : CustomTarget<Drawable>() {
            override fun onResourceReady(
                resource: android.graphics.drawable.Drawable,
                transition: com.bumptech.glide.request.transition.Transition<in android.graphics.drawable.Drawable>?
            ) {
                Log.d("WallpaperPagerAdapter", "smallUrl加载完成 position=$position")
                // 确保还是当前position
                if (holder.currentPosition == position) {
                    holder.imageView.setImageDrawable(resource)
                }
            }

            override fun onLoadCleared(placeholder: android.graphics.drawable.Drawable?) {
                // 清理资源
            }

            override fun onLoadFailed(errorDrawable: android.graphics.drawable.Drawable?) {
                Log.e("WallpaperPagerAdapter", "smallUrl加载失败 position=$position")
                if (holder.currentPosition == position && holder.itemView.isAttachedToWindow) {
                    holder.imageView.setBackgroundColor(R.color.light_gray)
                    holder.imageView.setImageResource(R.drawable.ic_loadingpic_failed)
                    holder.imageView.scaleType = ImageView.ScaleType.CENTER
                }
            }
        }
        // 先清除可能的错误状态
        holder.imageView.setBackgroundColor(0x00000000)
        holder.imageView.scaleType = ImageView.ScaleType.CENTER_CROP

        Glide.with(holder.itemView.context)
            .load(wallpaperItem.smallUrl)
            .dontAnimate()
            .skipMemoryCache(true) // 跳过内存缓存，确保每次都触发回调
            .into(smallUrlTarget)

        // 3. 加载fullUrl
        Glide.with(holder.itemView.context)
            .load(wallpaperItem.fullUrl)
            .dontAnimate()
            .diskCacheStrategy(com.bumptech.glide.load.engine.DiskCacheStrategy.ALL)
            .listener(object : RequestListener<android.graphics.drawable.Drawable> {
                override fun onLoadFailed(
                    e: GlideException?,
                    model: Any?,
                    target: Target<android.graphics.drawable.Drawable>?,
                    isFirstResource: Boolean
                ): Boolean {
                    Log.e("WallpaperPagerAdapter", "fullUrl加载失败 position=$position: ${e?.message}")
                    if (holder.currentPosition == position && holder.itemView.isAttachedToWindow) {
                        holder.loadingProgress.visibility = View.GONE

                        // 自定义错误显示：设置灰色背景和居中图标
                        holder.imageView.setBackgroundColor(R.color.light_gray)
                        holder.imageView.setImageResource(R.drawable.ic_loadingpic_failed)
                        holder.imageView.scaleType = ImageView.ScaleType.CENTER
                    }
                    // 通知加载失败
                    loadListener?.onImageLoadFailed(position, e ?: Exception("图片加载失败"))
                    return true
                }

                override fun onResourceReady(
                    resource: android.graphics.drawable.Drawable?,
                    model: Any?,
                    target: Target<android.graphics.drawable.Drawable>?,
                    dataSource: DataSource?,
                    isFirstResource: Boolean
                ): Boolean {
                    Log.d("WallpaperPagerAdapter", "fullUrl加载完成 position=$position")
                    if (holder.currentPosition == position && holder.itemView.isAttachedToWindow) {
                        holder.loadingProgress.visibility = View.GONE
                        // 清除可能的错误状态
                        holder.imageView.setBackgroundColor(0x00000000) // 透明背景
                        holder.imageView.scaleType = ImageView.ScaleType.CENTER_CROP // 恢复原来的缩放模式
                    }
                    // 通知加载成功
                    loadListener?.onImageLoadSuccess(position)
                    return false
                }
            })
            .into(holder.imageView)
    }

    override fun onViewRecycled(holder: ViewHolder) {
        super.onViewRecycled(holder)

        // 清理ImageView，Glide会自动取消相关请求
        Glide.with(holder.itemView.context).clear(holder.imageView)

        // 重置标识
        holder.currentPosition = -1
    }

    override fun getItemCount(): Int = wallpaperItems.size

    // 添加重新加载方法
    fun retryLoadImage(position: Int) {
        notifyItemChanged(position)
    }

    fun clearAllCache() {
        // 如果确实需要清除所有缓存，可以在Activity中调用但通常不需要手动清理
        // Glide.get(context).clearMemory()
    }
}