package com.all.pdfreader.pro.app.ui.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.all.pdfreader.pro.app.R
import com.all.pdfreader.pro.app.databinding.AdapterSplitPageItemBinding
import com.all.pdfreader.pro.app.model.PdfPageItem
import com.all.pdfreader.pro.app.util.AppUtils.dpToPx
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import java.io.File

class SplitPdfAdapter(
    private val pdfList: MutableList<PdfPageItem>,
    private val onItemClick: (PdfPageItem, Int) -> Unit
) : RecyclerView.Adapter<SplitPdfAdapter.PdfViewHolder>() {

    inner class PdfViewHolder(val binding: AdapterSplitPageItemBinding) :
        RecyclerView.ViewHolder(binding.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = PdfViewHolder(
        AdapterSplitPageItemBinding.inflate(
            LayoutInflater.from(parent.context), parent, false
        )
    )

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: PdfViewHolder, position: Int) {
        bindAll(holder, position)
    }

    // 支持 payload，局部刷新
    override fun onBindViewHolder(
        holder: PdfViewHolder, position: Int, payloads: MutableList<Any>
    ) {
        if (payloads.isEmpty()) {
            bindAll(holder, position) // 全量刷新
        } else {
            if (payloads.any { it == "selection" }) {
                bindSelectionOnly(holder, position)
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun bindAll(holder: PdfViewHolder, position: Int) {
        val item = pdfList[position]
        holder.binding.apply {
            //更新文字图片与选中状态
            pageNumberTv.text = "${item.pageIndex + 1}"
            if (item.previewFilePath != null) {
                Glide.with(holder.binding.root)
                    .load(File(item.previewFilePath ?: ""))
                    .transform(CenterCrop(), RoundedCorners(4.dpToPx(holder.binding.root.context)))
                    .into(image)
            }
            bindSelection(item, holder)
        }
        holder.binding.root.setOnClickListener {
            val pos = holder.bindingAdapterPosition
            if (pos != RecyclerView.NO_POSITION) {
                onItemClick(pdfList[pos], pos)
            }
        }
    }

    private fun bindSelectionOnly(holder: PdfViewHolder, position: Int) {
        val item = pdfList[position]
        bindSelection(item, holder)
    }

    //更新选中状态
    private fun bindSelection(item: PdfPageItem, holder: PdfViewHolder) {
        val b = holder.binding
        val selRes =
            if (item.isSelected) R.drawable.dr_item_page_img_sel_on_bg else R.drawable.dr_item_page_img_sel_off_bg
        b.selIv.setBackgroundResource(selRes)

        val bgRes = if (item.isSelected) R.drawable.dr_sel_on_frame else R.drawable.dr_sel_off_frame
        b.itemBgLayout.setBackgroundResource(bgRes)

        val pageBgRes =
            if (item.isSelected) R.drawable.dr_item_page_number_sel_on_bg else R.drawable.dr_item_page_number_sel_off_bg
        b.pageNumberTv.setBackgroundResource(pageBgRes)
    }


    override fun getItemCount() = pdfList.size

    fun updateItem(position: Int) = notifyItemChanged(position)

    // 只刷新选中状态
    fun setItemSelected(position: Int, selected: Boolean) {
        pdfList[position].isSelected = selected
        notifyItemChanged(position, "selection") // 这里的 payload 就是标记
    }

    fun getSelPages() = pdfList.count { it.isSelected }

    // 批量更新选中状态，用 payload 避免图片重新加载
    fun setAllSelected(selected: Boolean) {
        pdfList.forEach { it.isSelected = selected }
        notifyItemRangeChanged(0, pdfList.size, "selection")
    }
}