package com.useasy.callsdk.demo.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.useasy.callsdk.bean.DisplayNumber
import com.useasy.callsdk.demo.R

/**
 * 外显号码列表适配器
 */
class DisplayNumberAdapter(
    private val numbers: List<DisplayNumber>,
    private val selectedNumber: String? = null,
    private val onItemClick: (DisplayNumber) -> Unit
) : RecyclerView.Adapter<DisplayNumberAdapter.ViewHolder>() {

    private var currentSelectedNumber: String? = selectedNumber

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val tvNumber: TextView = itemView.findViewById(R.id.tv_number)
        val tvLocation: TextView = itemView.findViewById(R.id.tv_location)
        val ivSelected: ImageView = itemView.findViewById(R.id.iv_selected)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_display_number, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val number = numbers[position]
        holder.tvNumber.text = number.number ?: number.id ?: "未知号码"
        
        // 显示位置信息
        val location = buildString {
            if (!number.province.isNullOrEmpty()) {
                append(number.province)
            }
            if (!number.city.isNullOrEmpty()) {
                if (isNotEmpty()) append(" ")
                append(number.city)
            }
            if (isEmpty()) {
                append("未知地区")
            }
        }
        holder.tvLocation.text = location
        
        // 显示选中状态
        val isSelected = number.number == currentSelectedNumber || number.id == currentSelectedNumber
        holder.ivSelected.visibility = if (isSelected) View.VISIBLE else View.GONE
        
        holder.itemView.setOnClickListener {
            currentSelectedNumber = number.number ?: number.id
            notifyDataSetChanged()
            onItemClick(number)
        }
    }

    override fun getItemCount(): Int = numbers.size

    fun getSelectedNumber(): String? = currentSelectedNumber
}

