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

import android.annotation.SuppressLint
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.all.pdfreader.pro.app.R
import com.all.pdfreader.pro.app.databinding.AdapterPdfItemBinding
import com.all.pdfreader.pro.app.room.entity.PdfDocumentEntity
import com.all.pdfreader.pro.app.util.AppUtils.dpToPx
import com.all.pdfreader.pro.app.util.AppUtils.toHighlightedSpannable
import com.all.pdfreader.pro.app.util.FileUtils.toFormatFileSize
import com.all.pdfreader.pro.app.util.FileUtils.toSlashDate
import com.all.pdfreader.pro.app.util.PdfDiffCallback
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners

class SearchPdfAdapter(
    private val onItemClick: (PdfDocumentEntity) -> Unit,
    private val onMoreClick: (PdfDocumentEntity) -> Unit,
    private var showMoreButton: Boolean = false,  // 是否显示更多按钮
    private var showCheckButton: Boolean = false  // 是否显示选择框按钮
) : ListAdapter<PdfDocumentEntity, SearchPdfAdapter.PdfViewHolder>(PdfDiffCallback()) {
    private var searchKeyword: String? = null   // 保存当前搜索关键字
    inner class PdfViewHolder(val binding: AdapterPdfItemBinding) :
        RecyclerView.ViewHolder(binding.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PdfViewHolder {
        val binding = AdapterPdfItemBinding.inflate(
            LayoutInflater.from(parent.context), parent, false
        )
        return PdfViewHolder(binding)
    }

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

    override fun onBindViewHolder(holder: PdfViewHolder, position: Int, payloads: MutableList<Any>) {
        if (payloads.isNotEmpty()) {
            val payload = payloads[0] as? String
            bindItem(holder, getItem(position), payload)
        } else {
            super.onBindViewHolder(holder, position, payloads)
        }
    }

    private fun bindItem(holder: PdfViewHolder, item: PdfDocumentEntity, highlightKeyword: String?) {
        val context = holder.binding.root.context

        holder.binding.checkBtn.visibility = if (showCheckButton) View.VISIBLE else View.GONE
        holder.binding.moreBtn.visibility = if (showMoreButton) View.VISIBLE else View.GONE
        holder.binding.deleteBtn.visibility = View.GONE

        val keyword = highlightKeyword ?: searchKeyword
        holder.binding.tvFileName.text = if (keyword.isNullOrBlank()) {
            item.fileName
        } else {
            item.fileName.toHighlightedSpannable(keyword, holder.binding.root.context.getColor(R.color.icon_sel_on_color))
        }

        holder.binding.tvFileSize.text = item.fileSize.toFormatFileSize()
        holder.binding.tvFileDate.text = item.lastModified.toSlashDate()

        if (item.isPassword) {
            holder.binding.lockLayout.visibility = View.VISIBLE
            holder.binding.tvFileImg.visibility = View.GONE
        } else {
            holder.binding.lockLayout.visibility = View.GONE
            holder.binding.tvFileImg.visibility = View.VISIBLE
            Glide.with(context)
                .load(item.thumbnailPath)
                .transform(CenterCrop(), RoundedCorners(8.dpToPx(context)))
                .into(holder.binding.tvFileImg)
        }
        if (item.isFavorite) {
            holder.binding.collectState.visibility = View.VISIBLE
        } else {
            holder.binding.collectState.visibility = View.GONE
        }
        holder.binding.root.setOnClickListener { onItemClick(item) }
        holder.binding.moreBtn.setOnClickListener { onMoreClick(item) }
    }

    fun updateData(newList: List<PdfDocumentEntity>, onComplete: (() -> Unit)? = null) {
        submitList(newList.toList()) {
            onComplete?.invoke()
        }
    }

    /**
     * 搜索场景使用：只刷新高亮，不刷新整个列表
     */
    fun highlightItems(keyword: String) {
        searchKeyword = keyword
        for (i in 0 until itemCount) {
            notifyItemChanged(i, keyword)
        }
    }
}
