package com.gestoreasy.ui.adapters

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.DiffUtil

/**
 * Adapter base com suporte a lazy loading e paginação
 */
abstract class LazyLoadAdapter<T, VH : RecyclerView.ViewHolder>(
    private val pageSize: Int = 20
) : RecyclerView.Adapter<VH>() {
    
    private val items = mutableListOf<T>()
    private var isLoading = false
    private var hasMore = true
    private var onLoadMore: (() -> Unit)? = null
    
    fun setOnLoadMoreListener(listener: () -> Unit) {
        onLoadMore = listener
    }
    
    fun submitList(newItems: List<T>, hasMore: Boolean = true) {
        val diffCallback = createDiffCallback(items, newItems)
        val diffResult = DiffUtil.calculateDiff(diffCallback)
        
        items.clear()
        items.addAll(newItems)
        this.hasMore = hasMore
        this.isLoading = false
        
        diffResult.dispatchUpdatesTo(this)
    }
    
    fun appendItems(newItems: List<T>, hasMore: Boolean = true) {
        val startPosition = items.size
        items.addAll(newItems)
        this.hasMore = hasMore
        this.isLoading = false
        notifyItemRangeInserted(startPosition, newItems.size)
    }
    
    fun setLoading(loading: Boolean) {
        if (isLoading != loading) {
            isLoading = loading
            if (loading) {
                notifyItemInserted(items.size)
            } else {
                notifyItemRemoved(items.size)
            }
        }
    }
    
    override fun getItemCount(): Int {
        return items.size + if (isLoading) 1 else 0
    }
    
    protected fun getItem(position: Int): T? {
        return if (position < items.size) items[position] else null
    }
    
    protected fun getAllItems(): List<T> = items.toList()
    
    override fun onBindViewHolder(holder: VH, position: Int) {
        if (position == items.size - 5 && hasMore && !isLoading) {
            // Carregar mais quando faltam 5 itens
            isLoading = true
            onLoadMore?.invoke()
        }
        
        if (position < items.size) {
            onBindViewHolder(holder, items[position], position)
        } else if (position == items.size) {
            // Mostrar loading
            onBindLoadingViewHolder(holder)
        }
    }
    
    abstract fun onBindViewHolder(holder: VH, item: T, position: Int)
    abstract fun onBindLoadingViewHolder(holder: VH)
    abstract fun createDiffCallback(oldList: List<T>, newList: List<T>): DiffUtil.Callback
}

