package com.crm.chat.ui.chat

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.crm.chat.R
import com.crm.chat.data.model.ChatUserItem
import com.crm.chat.data.api.User
import com.crm.chat.ui.main.MainViewModel
import com.bumptech.glide.Glide

class GroupMemberAdapter(
    private val onUserClick: (Long) -> Unit
) : ListAdapter<ChatUserItem, GroupMemberAdapter.ViewHolder>(GroupMemberDiffCallback()) {

    private val mainViewModel: MainViewModel = MainViewModel.getInstance()

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

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val user = getItem(position)
        holder.bind(user)
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val userAvatarImageView: ImageView = itemView.findViewById(R.id.userAvatarImageView)
        private val userNameTextView: TextView = itemView.findViewById(R.id.userNameTextView)
        private val userEmailTextView: TextView = itemView.findViewById(R.id.userEmailTextView)
        private val userPhoneTextView: TextView = itemView.findViewById(R.id.userPhoneTextView)

        fun bind(user: ChatUserItem) {
            // Get user details from address book
            val userFromAddressBook = getUserFromAddressBook(user.userId)
            
            if (userFromAddressBook != null) {
                // Set user name from address book
                userNameTextView.text = userFromAddressBook.name
                
                // Set email and phone from address book
                userEmailTextView.text = userFromAddressBook.email
                userPhoneTextView.text = userFromAddressBook.phone ?: "Телефон не указан"
                
                // Load user avatar from address book
                loadUserAvatar(userFromAddressBook)
            } else {
                // Fallback to basic info if not in address book
                val userName = user.name ?: "User ${user.userId}"
                userNameTextView.text = userName
                userEmailTextView.text = "Email не указан"
                userPhoneTextView.text = "Телефон не указан"
                
                // Load user avatar using existing method
                loadUserAvatar(user.userId, userAvatarImageView)
            }

            // Set click listener
            itemView.setOnClickListener {
                onUserClick(user.userId)
            }
        }

        private fun loadUserAvatar(user: User) {
            if (user.avatarUrl != null && user.avatarUrl.isNotEmpty()) {
                // Load actual avatar image from URL with Glide
                Glide.with(userAvatarImageView.context)
                    .load(user.avatarUrl)
                    .circleCrop()
                    .placeholder(getUserColor(user.id)) // Show color while loading
                    .error(object : com.bumptech.glide.request.target.CustomTarget<android.graphics.drawable.Drawable>() {
                        override fun onResourceReady(resource: android.graphics.drawable.Drawable, transition: com.bumptech.glide.request.transition.Transition<in android.graphics.drawable.Drawable>?) {
                            // Avatar loaded successfully
                            userAvatarImageView.setImageDrawable(resource)
                        }

                        override fun onLoadCleared(placeholder: android.graphics.drawable.Drawable?) {
                            // Show initials when avatar fails to load
                            showInitialsAvatar(user)
                        }
                    })
                    .into(userAvatarImageView)
            } else {
                // No avatar URL, show initials
                showInitialsAvatar(user)
            }
        }

        private fun loadUserAvatar(userId: Long, imageView: ImageView) {
            val avatarUrl = mainViewModel.getUserAvatarUrl(userId)
            val userName = mainViewModel.getUserName(userId)

            if (avatarUrl != null && avatarUrl.isNotEmpty()) {
                // Load actual avatar image from URL with Glide
                Glide.with(imageView.context)
                    .load(avatarUrl)
                    .circleCrop()
                    .placeholder(getUserColor(userId)) // Show color while loading
                    .error(object : com.bumptech.glide.request.target.CustomTarget<android.graphics.drawable.Drawable>() {
                        override fun onResourceReady(resource: android.graphics.drawable.Drawable, transition: com.bumptech.glide.request.transition.Transition<in android.graphics.drawable.Drawable>?) {
                            // Avatar loaded successfully
                            imageView.setImageDrawable(resource)
                        }

                        override fun onLoadCleared(placeholder: android.graphics.drawable.Drawable?) {
                            // Show initials when avatar fails to load
                            showInitialsAvatar(userId, userName, imageView)
                        }
                    })
                    .into(imageView)
            } else {
                // No avatar URL, show initials
                showInitialsAvatar(userId, userName, imageView)
            }
        }

        private fun showInitialsAvatar(user: User) {
            // Generate initials from user name
            val initials = user.name.split(" ").let { parts ->
                when (parts.size) {
                    1 -> parts[0].take(1).uppercase()
                    2 -> "${parts[0].take(1)}${parts[1].take(1)}".uppercase()
                    else -> parts.firstOrNull()?.take(1)?.uppercase() ?: "U"
                }
            }

            // Background color for the avatar
            val backgroundColor = getUserColor(user.id)

            // Create circular bitmap with initials
            val size = 192
            val bitmap = android.graphics.Bitmap.createBitmap(size, size, android.graphics.Bitmap.Config.ARGB_8888)
            val canvas = android.graphics.Canvas(bitmap)

            // Draw circle background
            val circlePaint = android.graphics.Paint().apply {
                color = backgroundColor
                isAntiAlias = true
                style = android.graphics.Paint.Style.FILL
            }
            canvas.drawCircle(size / 2f, size / 2f, size / 2f, circlePaint)

            // Draw initials text
            val textPaint = android.graphics.Paint().apply {
                color = android.graphics.Color.WHITE
                textSize = size * 0.5f // Larger text for better visibility
                textAlign = android.graphics.Paint.Align.CENTER
                isAntiAlias = true
                typeface = android.graphics.Typeface.DEFAULT_BOLD
            }

            val xPos = size / 2f
            val yPos = size / 2f - (textPaint.descent() + textPaint.ascent()) / 2f
            canvas.drawText(initials, xPos, yPos, textPaint)

            // Clear any background color from ImageView (let the bitmap be fully circular)
            userAvatarImageView.setBackgroundColor(android.graphics.Color.TRANSPARENT)
            userAvatarImageView.setImageBitmap(bitmap)
        }

        private fun showInitialsAvatar(userId: Long, userName: String, imageView: ImageView) {
            // Generate initials from user name
            val initials = userName.split(" ").let { parts ->
                when (parts.size) {
                    1 -> parts[0].take(1).uppercase()
                    2 -> "${parts[0].take(1)}${parts[1].take(1)}".uppercase()
                    else -> parts.firstOrNull()?.take(1)?.uppercase() ?: "U"
                }
            }

            // Background color for the avatar
            val backgroundColor = getUserColor(userId)

            // Create circular bitmap with initials
            val size = 192
            val bitmap = android.graphics.Bitmap.createBitmap(size, size, android.graphics.Bitmap.Config.ARGB_8888)
            val canvas = android.graphics.Canvas(bitmap)

            // Draw circle background
            val circlePaint = android.graphics.Paint().apply {
                color = backgroundColor
                isAntiAlias = true
                style = android.graphics.Paint.Style.FILL
            }
            canvas.drawCircle(size / 2f, size / 2f, size / 2f, circlePaint)

            // Draw initials text
            val textPaint = android.graphics.Paint().apply {
                color = android.graphics.Color.WHITE
                textSize = size * 0.5f // Larger text for better visibility
                textAlign = android.graphics.Paint.Align.CENTER
                isAntiAlias = true
                typeface = android.graphics.Typeface.DEFAULT_BOLD
            }

            val xPos = size / 2f
            val yPos = size / 2f - (textPaint.descent() + textPaint.ascent()) / 2f
            canvas.drawText(initials, xPos, yPos, textPaint)

            // Clear any background color from ImageView (let the bitmap be fully circular)
            imageView.setBackgroundColor(android.graphics.Color.TRANSPARENT)
            imageView.setImageBitmap(bitmap)
        }

        private fun getUserColor(userId: Long): Int {
            // Generate a color based on user ID for consistency
            val colors = intArrayOf(
                android.graphics.Color.parseColor("#E53935"), // Red
                android.graphics.Color.parseColor("#1E88E5"), // Blue
                android.graphics.Color.parseColor("#43A047"), // Green
                android.graphics.Color.parseColor("#FB8C00"), // Orange
                android.graphics.Color.parseColor("#8E24AA"), // Purple
                android.graphics.Color.parseColor("#00ACC1"), // Cyan
                android.graphics.Color.parseColor("#FDD835"), // Yellow
                android.graphics.Color.parseColor("#6D4C41"), // Brown
            )
            return colors[(userId % colors.size).toInt()]
        }

        private fun getUserFromAddressBook(userId: Long): User? {
            // Get the address book state from MainViewModel
            val addressBookState = mainViewModel.addressBookState.value
            
            return when (addressBookState) {
                is com.crm.chat.ui.main.MainViewModel.AddressBookState.Success -> {
                    addressBookState.users.find { it.id == userId }
                }
                else -> {
                    // If address book is not loaded, try to get from cache
                    val cachedUser = mainViewModel.userCache[userId]
                    if (cachedUser != null) {
                        cachedUser
                    } else {
                        null
                    }
                }
            }
        }
    }
}

class GroupMemberDiffCallback : DiffUtil.ItemCallback<ChatUserItem>() {
    override fun areItemsTheSame(oldItem: ChatUserItem, newItem: ChatUserItem): Boolean {
        return oldItem.id == newItem.id
    }

    override fun areContentsTheSame(oldItem: ChatUserItem, newItem: ChatUserItem): Boolean {
        return oldItem == newItem
    }
}
