package com.seatel.mobilehall.ui.profile.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.seatel.mobilehall.databinding.HolderDialogChooseAccountItemBinding
import com.seatel.mobilehall.util.BottomAccountChooserDialog

class BottomAccountChooserAdapter :
    RecyclerView.Adapter<BottomAccountChooserAdapter.BottomChooserViewHolder>() {

    private var bottomChooserModels =
        ArrayList<BottomAccountChooserDialog.BottomAccountChooserModel>()
    private var onItemClick: OnItemClick? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BottomChooserViewHolder {
        // Use ViewBinding to inflate the layout and bind the view
        val binding = HolderDialogChooseAccountItemBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return BottomChooserViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return bottomChooserModels.size
    }

    override fun onBindViewHolder(holder: BottomChooserViewHolder, position: Int) {
        val model = bottomChooserModels[position]

        // Access the views through the binding object
        holder.binding.tvChooser.text = model.name

        // Hide/show elements based on position
        holder.binding.tvPlus.visibility =
            if (position == bottomChooserModels.size - 1) View.VISIBLE else View.GONE
        holder.binding.viewLine.visibility = if (position == 0) View.GONE else View.VISIBLE

        // Manage visibility of deleted number indicator
        holder.binding.deletedNumber.visibility = if (model.deleted) View.VISIBLE else View.GONE

        // Set click listeners
        holder.binding.root.setOnClickListener {
            onItemClick?.onClick(position, model)
        }
        holder.binding.deletedNumber.setOnClickListener {
            onItemClick?.onDelete(position, model)
        }
    }

    // Interface for item click handling
    interface OnItemClick {
        fun onClick(position: Int, data: BottomAccountChooserDialog.BottomAccountChooserModel)
        fun onDelete(position: Int, data: BottomAccountChooserDialog.BottomAccountChooserModel)
    }

    // Method to update the list of items
    fun addItems(
        bottomChooserModels: ArrayList<BottomAccountChooserDialog.BottomAccountChooserModel>,
        onItemClick: OnItemClick
    ) {
        this.onItemClick = onItemClick
        this.bottomChooserModels.clear()
        this.bottomChooserModels.addAll(bottomChooserModels)
        notifyDataSetChanged()  // Notify the adapter that the data has changed
    }

    // ViewHolder class using ViewBinding
    class BottomChooserViewHolder(val binding: HolderDialogChooseAccountItemBinding) :
        RecyclerView.ViewHolder(binding.root)
}
