package com.gestoreasy.ui.routes

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.gestoreasy.database.entities.Client
import com.gestoreasy.databinding.ItemClientRouteBinding

class ClientsRouteAdapter(
    private val onClientSelected: (Client, Boolean) -> Unit,
    private val onRouteClick: (Client) -> Unit
) : ListAdapter<Client, ClientsRouteAdapter.ClientViewHolder>(ClientDiffCallback()) {
    
    private val selectedClients = mutableSetOf<Long>()
    
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ClientViewHolder {
        val binding = ItemClientRouteBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ClientViewHolder(binding, onClientSelected, onRouteClick)
    }
    
    override fun onBindViewHolder(holder: ClientViewHolder, position: Int) {
        val client = getItem(position)
        holder.bind(client, selectedClients.contains(client.id))
    }
    
    fun clearSelection() {
        selectedClients.clear()
        notifyDataSetChanged()
    }
    
    inner class ClientViewHolder(
        private val binding: ItemClientRouteBinding,
        private val onClientSelected: (Client, Boolean) -> Unit,
        private val onRouteClick: (Client) -> Unit
    ) : RecyclerView.ViewHolder(binding.root) {
        
        fun bind(client: Client, isSelected: Boolean) {
            binding.checkClient.isChecked = isSelected
            binding.textClientName.text = client.nome
            binding.textClientAddress.text = client.endereco ?: "Endereço não informado"
            binding.textClientCity.text = "${client.cidade ?: ""} - ${client.estado ?: ""}"
            
            binding.checkClient.setOnCheckedChangeListener { _, checked ->
                if (checked) {
                    selectedClients.add(client.id)
                } else {
                    selectedClients.remove(client.id)
                }
                onClientSelected(client, checked)
            }
            
            binding.btnRouteToClient.setOnClickListener {
                onRouteClick(client)
            }
        }
    }
    
    class ClientDiffCallback : DiffUtil.ItemCallback<Client>() {
        override fun areItemsTheSame(oldItem: Client, newItem: Client): Boolean {
            return oldItem.id == newItem.id
        }
        
        override fun areContentsTheSame(oldItem: Client, newItem: Client): Boolean {
            return oldItem == newItem
        }
    }
}

