package com.rugvedsarika.docscan.ui.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.rugvedsarika.docscan.data.entity.Document
import com.rugvedsarika.docscan.databinding.ItemDocumentBinding
import java.text.SimpleDateFormat
import java.util.*

class DocumentAdapter(
    private val onDocumentClick: (Document) -> Unit,
    private val onMoreClick: (View, Document) -> Unit,
    private val onLongClick: (Document) -> Unit,
    private val onSelectionChanged: (Int) -> Unit
) : ListAdapter<Document, DocumentAdapter.DocumentViewHolder>(DocumentDiffCallback()) {

    var isSelectionMode = false
        set(value) {
            field = value
            if (!value) selectedIds.clear()
            notifyDataSetChanged()
        }
    
    val selectedIds = mutableSetOf<Long>()

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

    override fun onBindViewHolder(holder: DocumentViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    inner class DocumentViewHolder(private val binding: ItemDocumentBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(document: Document) {
            binding.tvName.text = document.name
            binding.tvDate.text = formatDate(document.createdDate)
            
            if (document.isLocked) {
                binding.ivLock.visibility = View.VISIBLE
                binding.ivThumbnail.alpha = 0.3f
            } else {
                binding.ivLock.visibility = View.GONE
                binding.ivThumbnail.alpha = 1.0f
            }

            Glide.with(binding.ivThumbnail.context)
                .load(document.thumbnailPath)
                .placeholder(android.R.drawable.ic_menu_gallery)
                .into(binding.ivThumbnail)

            // Selection Mode UI
            if (isSelectionMode) {
                binding.cbSelect.visibility = View.VISIBLE
                binding.cbSelect.isChecked = selectedIds.contains(document.id)
                binding.btnMore.visibility = View.GONE
            } else {
                binding.cbSelect.visibility = View.GONE
                binding.btnMore.visibility = View.VISIBLE
            }

            binding.root.setOnClickListener {
                if (isSelectionMode) {
                    toggleSelection(document.id)
                } else {
                    onDocumentClick(document)
                }
            }

            binding.root.setOnLongClickListener {
                if (!isSelectionMode) {
                    val pos = bindingAdapterPosition
                    if (pos != RecyclerView.NO_POSITION) {
                        val doc = getItem(pos)
                        onLongClick(doc)
                        toggleSelection(doc.id)
                        true
                    } else false
                } else false
            }

            binding.cbSelect.setOnClickListener {
                toggleSelection(document.id)
            }

            binding.btnMore.setOnClickListener { onMoreClick(it, document) }
        }

        private fun toggleSelection(id: Long) {
            if (selectedIds.contains(id)) {
                selectedIds.remove(id)
            } else {
                selectedIds.add(id)
            }
            notifyItemChanged(bindingAdapterPosition)
            onSelectionChanged(selectedIds.size)
        }

        private fun formatDate(timestamp: Long): String {
            val sdf = SimpleDateFormat("MMM dd, yyyy", Locale.getDefault())
            return sdf.format(Date(timestamp))
        }
    }

    fun getSelectedDocuments(): List<Document> {
        return currentList.filter { selectedIds.contains(it.id) }
    }

    class DocumentDiffCallback : DiffUtil.ItemCallback<Document>() {
        override fun areItemsTheSame(oldItem: Document, newItem: Document): Boolean = oldItem.id == newItem.id
        override fun areContentsTheSame(oldItem: Document, newItem: Document): Boolean = oldItem == newItem
    }
}
