package com.adealink.weparty.playmate.userpush

import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.adealink.frame.base.Rlt
import com.adealink.frame.base.fastLazy
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.router.Router
import com.adealink.weparty.commonui.BaseFragment
import com.adealink.weparty.commonui.ext.dp
import com.adealink.weparty.commonui.ext.gone
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.commonui.recycleview.adapter.MultiTypeListAdapter
import com.adealink.weparty.commonui.recycleview.itemdecoration.VerticalSpaceItemDecoration
import com.adealink.weparty.commonui.toast.util.showFailedToast
import com.adealink.weparty.commonui.toast.util.showToast
import com.adealink.weparty.module.im.IM
import com.adealink.weparty.module.im.data.SessionSource
import com.adealink.weparty.module.im.data.sendIMMessageLD
import com.adealink.weparty.module.playmate.PlaymateModule
import com.adealink.weparty.module.profile.Profile
import com.adealink.weparty.playmate.R
import com.adealink.weparty.playmate.databinding.FragmentUserPushBinding
import com.adealink.weparty.playmate.userpush.adapter.UserPushItemViewBinder
import com.adealink.weparty.playmate.userpush.data.UserPushItemData
import com.adealink.weparty.playmate.userpush.viewmodel.UserPushViewModel
import com.adealink.weparty.playmate.viewmodel.PlaymateViewModelFactory
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import kotlinx.coroutines.launch
import com.adealink.weparty.R as APP_R

class UserPushFragment : BaseFragment(R.layout.fragment_user_push) {
    private val binding by viewBinding(FragmentUserPushBinding::bind)
    private val viewModel by activityViewModels<UserPushViewModel> { PlaymateViewModelFactory() }
    private val listAdapter by fastLazy { MultiTypeListAdapter<UserPushItemData>() }
    override fun initViews() {
        super.initViews()
        binding.vRefresh.setEnableRefresh(true)
        binding.vRefresh.setEnableLoadMore(false)
        binding.vRefresh.setEnableAutoLoadMore(false)
        binding.vRefresh.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                viewModel.pullUserPushList()
            }


            override fun onLoadMore(refreshLayout: RefreshLayout) {
            }
        })

        listAdapter.register(
            UserPushItemViewBinder(
                goProfile = { uid ->
                    this@UserPushFragment.goProfile(uid)
                },
                goSession = { uid ->
                    this@UserPushFragment.goSession(uid)
                }
            ))
        binding.rvVisitor.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
        binding.rvVisitor.adapter = listAdapter
        binding.rvVisitor.addItemDecoration(
            VerticalSpaceItemDecoration(
                0,
                firstSpaceHeight = 6.dp()
            )
        )
    }

    override fun loadData() {
        super.loadData()
        viewModel.pullUserPushList()
    }

    override fun observeViewModel() {
        super.observeViewModel()
        viewModel.userPushListLD.observe(viewLifecycleOwner) {
            if (it.isNullOrEmpty()) {
                binding.rvVisitor.gone()
                binding.vErrorView.show(
                    errorEmptyResId = APP_R.drawable.common_follow_list_empty_ic,
                    title = APP_R.string.commonui_list_empty
                )
            } else {
                listAdapter.submitList(it)
                binding.rvVisitor.show()
                binding.vErrorView.gone()
            }
        }
        viewModel.userPushListRltLD.observe(viewLifecycleOwner) { rlt ->
            binding.vRefresh.finishRefresh()
            binding.vRefresh.finishLoadMore()
            showFailedToast(rlt)
        }
        sendIMMessageLD.observe(viewLifecycleOwner) { msg ->
            msg ?: return@observe
            viewModel.notifyContactedChanged(msg.userId) { pos ->
                listAdapter.notifyItemChanged(pos)
            }
        }
    }

    private fun goProfile(uid: String) {
        val act = activity ?: return
        Router.build(act, Profile.UserProfile.PATH)
            .putExtra(Profile.Common.EXTRA_UID, uid)
            .start()
    }

    private fun goSession(uid: String) {
        val act = activity ?: return
        lifecycleScope.launch {
            this@UserPushFragment.showLoading()
            val rlt = PlaymateModule.isUserPushChatAvailable(uid)
            this@UserPushFragment.dismissLoading()
            when (rlt) {
                is Rlt.Failed -> {
                    showFailedToast(rlt)
                }

                is Rlt.Success -> {
                    val available = rlt.data
                    if (available) {
                        Router.build(act, IM.Session.PATH)
                            .putExtra(IM.Session.EXTRA_CHAT_ID, uid)
                            .putExtra(IM.Session.EXTRA_CHAT_SOURCE, SessionSource.USER_PUSH.source)
                            .start()
                    } else {
                        showToast(APP_R.string.playmate_user_push_chat_limit)
                    }
                }
            }
        }
    }

}