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

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

class PdfAdapter(
    private var pdfList: MutableList<PdfDocumentEntity>,
    private val onItemClick: (PdfDocumentEntity) -> Unit = {},
    private val onMoreClick: (PdfDocumentEntity) -> Unit = {},
    private val onLongClick: (PdfDocumentEntity) -> Unit = {},
    private val onSelectModelItemClick: (Int) -> Unit = {},
    private val onDeleteItemClick: (PdfDocumentEntity, Int) -> Unit = { _, _ -> },
    private var enableLongClick: Boolean = true,
    private var showMoreButton: Boolean = true,  // 是否显示更多按钮
    private var showCheckButton: Boolean = false,  // 是否显示选择框按钮
    private var isMultiSelectMode: Boolean = false, // 是否进入多选模式
    private var showDeleteButton: Boolean = false // 是否显示删除按钮
) : RecyclerView.Adapter<PdfAdapter.PdfViewHolder>() {

    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", "NotifyDataSetChanged")
    override fun onBindViewHolder(holder: PdfViewHolder, position: Int) {
        val item = pdfList[position]
        holder.binding.tvFileName.text = item.fileName
        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(holder.binding.root).load(item.thumbnailPath)
                .transform(CenterCrop(), RoundedCorners(4.dpToPx(holder.binding.root.context)))
                .into(holder.binding.tvFileImg)
        }
        if (item.isFavorite) {
            holder.binding.collectState.visibility = View.VISIBLE
        } else {
            holder.binding.collectState.visibility = View.GONE
        }
        if (isMultiSelectMode) {
            holder.binding.checkBtn.visibility = View.VISIBLE
            holder.binding.moreBtn.visibility = View.GONE
            holder.binding.deleteBtn.visibility = View.GONE
        } else {
            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 = if (showDeleteButton) View.VISIBLE else View.GONE
        }
        holder.binding.checkbox.isChecked = item.isSelected
        holder.binding.fileTv.text = FileUtils.getParentFolderName(item.filePath)
        holder.binding.root.setOnClickListener {
            if (isMultiSelectMode) {
                item.isSelected = !item.isSelected
                notifyItemChanged(position)
                onSelectModelItemClick(getSelectedItems().size)
            } else {
                onItemClick(item)
            }
        }
        holder.binding.moreBtn.setOnClickListener {
            onMoreClick(item)
        }
        if (enableLongClick) {
            holder.binding.root.setOnLongClickListener {
                if (!isMultiSelectMode) {
                    isMultiSelectMode = true
                    item.isSelected = !item.isSelected
                    notifyDataSetChanged()
                    onLongClick(item)
                }
                true
            }
        } else {
            holder.binding.root.setOnLongClickListener(null) // 禁用长按
        }

        holder.binding.deleteBtn.setOnClickListener {
            onDeleteItemClick(item, holder.bindingAdapterPosition)
        }
    }

    override fun getItemCount(): Int = pdfList.size

    @SuppressLint("NotifyDataSetChanged")
    fun updateData(newList: List<PdfDocumentEntity>) {
        pdfList.clear()
        pdfList.addAll(newList)
        notifyDataSetChanged()
    }

    fun getCurrentList(): List<PdfDocumentEntity> {
        return pdfList
    }

    fun removeItem(position: Int) {
        pdfList.removeAt(position)
        notifyItemRemoved(position)
    }

    // 退出多选模式
    @SuppressLint("NotifyDataSetChanged")
    fun exitMultiSelectMode() {
        isMultiSelectMode = false
        pdfList.forEach { it.isSelected = false }
        notifyDataSetChanged()
    }

    @SuppressLint("NotifyDataSetChanged")
    fun toggleSelectAll() {
        val allSelected = pdfList.all { it.isSelected }
        if (allSelected) deselectAll() else selectAll()
    }

    // 全选
    fun selectAll() {
        pdfList.forEach { it.isSelected = true }
        notifyDataSetChanged()
    }

    // 取消全选
    fun deselectAll() {
        pdfList.forEach { it.isSelected = false }
        notifyDataSetChanged()
    }

    // 判断是否全选
    fun isAllSelected(): Boolean = pdfList.isNotEmpty() && pdfList.all { it.isSelected }

    // 获取已选中的 item
    fun getSelectedItems(): List<PdfDocumentEntity> {
        return pdfList.filter { it.isSelected }
    }

    fun getIsMultiSelectMode(): Boolean {
        return isMultiSelectMode
    }

    fun setIsMultiSelectMode(b: Boolean) {
        isMultiSelectMode = b
        notifyDataSetChanged()
    }
}
