package com.adealink.weparty.im.list.adapter.viewbinder

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.adealink.frame.base.AppBase
import com.adealink.frame.dot.NumDot
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.ext.gone
import com.adealink.weparty.commonui.ext.isViewValid
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.commonui.recycleview.adapter.BindingViewHolder
import com.adealink.weparty.commonui.recycleview.adapter.multitype.ItemViewBinder
import com.adealink.weparty.im.databinding.LayoutSessionListItemBinding
import com.adealink.weparty.im.list.adapter.data.CommonSessionListItemData
import com.adealink.weparty.im.list.adapter.data.getMessageDisplayString
import com.adealink.weparty.im.list.adapter.data.getMessageDisplayTime
import com.adealink.weparty.im.listener.IUserInfoListener
import com.adealink.weparty.module.profile.ProfileModule
import com.adealink.weparty.module.profile.data.UserInfo
import com.adealink.weparty.util.formatTimeStr
import com.tencent.qcloud.tuikit.tuiconversation.minimalistui.interfaces.OnConversationAdapterListener


class SessionListItemViewBinder(
    private val lifecycleOwner: LifecycleOwner,
    private val listener: OnConversationAdapterListener,
    private val onAvatarClick: (uid: String) -> Unit,
    private val userInfoListener: IUserInfoListener,
) :
    ItemViewBinder<CommonSessionListItemData, SessionListItemViewBinder.ViewHolder>() {

    override fun onBindViewHolder(
        holder: ViewHolder,
        item: CommonSessionListItemData
    ) {
        holder.update(holder, item)
    }

    override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): ViewHolder {
        return ViewHolder(
            LayoutSessionListItemBinding.inflate(inflater, parent, false)
        )
    }


    override fun onViewDetachedFromWindow(holder: ViewHolder) {
        super.onViewDetachedFromWindow(holder)
        holder.binding.vOnline.onStop()
    }

    override fun onViewRecycled(holder: ViewHolder) {
        holder.binding.vOnline.onStop()
        super.onViewRecycled(holder)
    }


    inner class ViewHolder(
        binding: LayoutSessionListItemBinding,
    ) : BindingViewHolder<LayoutSessionListItemBinding>(binding) {

        private var item: CommonSessionListItemData? = null

        fun initView() {

        }

        private val onlineObserver = object : Observer<Boolean> {

            var holder: ViewHolder? = null

            override fun onChanged(value: Boolean) {
                val holder = holder
                if (holder == null || !holder.isViewValid()) {
                    return
                }
                updateUserOnline(value)
            }
        }

        fun update(holder: ViewHolder, item: CommonSessionListItemData) {
            resetItem(this.item)
            this.item = item
            onlineObserver.holder = holder
            binding.root.onClick {
                listener.onItemClick(it, item.data.type, item.data)
            }

            val uid = item.data.id
            binding.ivAvatar.onClick {
                onAvatarClick.invoke(item.data.id)
            }
            userInfoListener.getUserInfo(uid) { userInfo ->
                updateUserInfo(item, userInfo)
            }

            val online = ProfileModule.isUserOnline(uid)
            updateUserOnline(online)
            ProfileModule.observeUserOnline(uid).observe(lifecycleOwner, onlineObserver)
            setLastMessageAndStatus(binding, item)

            // TODO: 长按测试用
            if (!AppBase.isRelease) {
                binding.root.setOnLongClickListener {
                    listener.onItemLongClick(it, item.data)
                    true
                }
            }
        }

        private fun resetItem(item: CommonSessionListItemData?) {
            item ?: return
            val uid = item.data.id
            ProfileModule.observeUserOnline(uid).removeObserver(onlineObserver)
        }

        private fun setLastMessageAndStatus(
            binding: LayoutSessionListItemBinding,
            item: CommonSessionListItemData,
        ) {
            val conversation = item.data
            binding.tvDesc.text = conversation.getMessageDisplayString()
            setLastMessageTime(conversation.getMessageDisplayTime())
            binding.vDot.show(NumDot(conversation.unRead))
        }

        private fun setLastMessageTime(timeTs: Long?) {
            binding.tvTime.text = timeTs?.formatTimeStr()
        }

        private fun updateUserInfo(
            item: CommonSessionListItemData,
            userInfo: UserInfo?
        ) {
            binding.ivAvatar.setImageUrl(userInfo?.avatar)
            binding.tvTitle.text = userInfo?.getUserNoteName() ?: item.data.title
        }

        private fun updateUserOnline(online: Boolean) {
            if (online) {
                binding.vOnline.show()
                binding.vOnline.onStart()
            } else {
                binding.vOnline.gone()
                binding.vOnline.onStop()
            }
        }
    }
}