package com.adealink.weparty.profile.ui.about

import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
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.recycleview.adapter.MultiTypeListAdapter
import com.adealink.weparty.commonui.recycleview.diffutil.BaseListDiffUtil
import com.adealink.weparty.commonui.recycleview.itemdecoration.VerticalSpaceItemDecoration
import com.adealink.weparty.commonui.toast.util.showFailedToast
import com.adealink.weparty.module.playmate.Playmate
import com.adealink.weparty.module.profile.ProfileModule
import com.adealink.weparty.module.profile.data.UserPlaymateSkill
import com.adealink.weparty.profile.R
import com.adealink.weparty.profile.databinding.FragmentProfileBinding
import com.adealink.weparty.profile.dynamic.data.deleteDynamicLD
import com.adealink.weparty.profile.dynamic.data.likeDynamicLD
import com.adealink.weparty.profile.dynamic.data.publishNewCommentLD
import com.adealink.weparty.profile.dynamic.data.publishNewDynamicLD
import com.adealink.weparty.profile.dynamic.fragment.dialog.DynamicTalkDialog
import com.adealink.weparty.profile.dynamic.viewmodel.DynamicListViewModel
import com.adealink.weparty.profile.dynamic.viewmodel.DynamicViewModel
import com.adealink.weparty.profile.ui.about.adapter.DynamicTitleViewBinder
import com.adealink.weparty.profile.ui.about.adapter.DynamicViewBinder
import com.adealink.weparty.profile.ui.about.adapter.InterestsViewBinder
import com.adealink.weparty.profile.ui.about.adapter.IntroduceViewBinder
import com.adealink.weparty.profile.ui.about.adapter.ProfileEmptyViewBinder
import com.adealink.weparty.profile.ui.about.adapter.SkillsViewBinder
import com.adealink.weparty.profile.ui.about.data.BaseProfileData
import com.adealink.weparty.profile.ui.about.data.DynamicItemData
import com.adealink.weparty.profile.ui.about.viewmodel.ProfilePageViewModel
import com.adealink.weparty.profile.viewmodel.ProfileViewModel
import com.adealink.weparty.profile.viewmodel.ProfileViewModelFactory
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener


class ProfileFragment : BaseFragment(R.layout.fragment_profile) {

    private val binding by viewBinding(FragmentProfileBinding::bind)

    private val profileViewModel by activityViewModels<ProfileViewModel> { ProfileViewModelFactory() }
    private val profilePageViewModel by viewModels<ProfilePageViewModel> { ProfileViewModelFactory() }
    private val dynamicListViewModel by viewModels<DynamicListViewModel> { ProfileViewModelFactory() }

    private val dynamicViewModel by viewModels<DynamicViewModel> { ProfileViewModelFactory() }

    private val profileAdapter by fastLazy { MultiTypeListAdapter<BaseProfileData>(BaseListDiffUtil()) }
    private lateinit var layoutManager: LinearLayoutManager

    private lateinit var dynamicViewBinder: DynamicViewBinder

    override fun initViews() {
        super.initViews()
        profileAdapter.register(IntroduceViewBinder())
        profileAdapter.register(InterestsViewBinder())
        profileAdapter.register(
            SkillsViewBinder(
                isSelf = {
                    profileViewModel.userInfoLD?.value?.uid == ProfileModule.getMyUid()
                },
                goOrder = {
                    goPlaymateDetail(it)
                }
            ))
        profileAdapter.register(ProfileEmptyViewBinder())
        profileAdapter.register(DynamicTitleViewBinder())
        dynamicViewBinder = DynamicViewBinder(
            this@ProfileFragment.lifecycle,
            onTalkClick = { item, position ->
                DynamicTalkDialog().apply {
                    setDynamicId(item.dynamic.id)
                }.show(childFragmentManager)
            },
            onLikeClick = { item, position ->
                likeDynamic(item, position)
            }
        )
        profileAdapter.register(dynamicViewBinder)

        binding.vRefresh.setEnableRefresh(true)
        binding.vRefresh.setEnableLoadMore(true)
        binding.vRefresh.setEnableAutoLoadMore(false)
        binding.vRefresh.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                dynamicListViewModel.reloadDynamic()
            }


            override fun onLoadMore(refreshLayout: RefreshLayout) {
                dynamicListViewModel.loadMoreDynamic()
            }
        })

        binding.rvContent.adapter = profileAdapter
        binding.rvContent.layoutManager =
            LinearLayoutManager(context, RecyclerView.VERTICAL, false).also {
                layoutManager = it
            }
        binding.rvContent.addItemDecoration(
            VerticalSpaceItemDecoration(0, 40.dp(), 16.dp())
        )
        binding.rvContent.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                // 仅在滚动停止时检测并播放
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    playTopDynamicVideo(recyclerView)
                }
            }
        })
    }


    private fun playTopDynamicVideo(recyclerView: RecyclerView) {
        // 获取第一个完全可见的item位置
        val firstCompletelyVisiblePos = layoutManager.findFirstCompletelyVisibleItemPosition()
        val lastCompletelyVisiblePos = layoutManager.findLastCompletelyVisibleItemPosition()
        var dynamicVideoIndex = -1
        for (i in firstCompletelyVisiblePos..lastCompletelyVisiblePos) {
            val item = profileAdapter.getItem(i)
            if (item is DynamicItemData && item.dynamic.isVideo() && item.dynamic.isVideoMediaAvailable()) {
                dynamicVideoIndex = i
            }
        }
        if (dynamicVideoIndex != RecyclerView.NO_POSITION) {
            // 遍历所有当前活跃的ViewHolder
            dynamicViewBinder.playVideo(dynamicVideoIndex)
        }
    }

    override fun observeViewModel() {
        super.observeViewModel()
        profileViewModel.userInfoLD.observe(viewLifecycleOwner) { userInfo ->
            profilePageViewModel.setUserInfo(userInfo)
            dynamicListViewModel.pullDynamicIfEmpty(userInfo?.uid)
        }
        dynamicListViewModel.dynamicListRltLD.observe(viewLifecycleOwner) { rlt ->
            binding.vRefresh.finishRefresh()
            binding.vRefresh.finishLoadMore()
            binding.vRefresh.setEnableLoadMore(dynamicListViewModel.hasMoreDynamic())
            showFailedToast(rlt)
        }
        dynamicListViewModel.dynamicListLD.observe(viewLifecycleOwner) {
            profilePageViewModel.setDynamicList(it)
        }
        profilePageViewModel.profileItemLD.observe(viewLifecycleOwner) {
            profileAdapter.submitList(it)
        }
        publishNewDynamicLD.observeWithoutCache(viewLifecycleOwner) {
            dynamicListViewModel.onPublishNewDynamic()
        }
        deleteDynamicLD.observeWithoutCache(viewLifecycleOwner) {
            dynamicListViewModel.onDynamicDelete(it)
        }
        publishNewCommentLD.observeWithoutCache(viewLifecycleOwner) {
            profilePageViewModel.onDynamicNewComment(it.dynamicId) { position ->
                profileAdapter.notifyItemChanged(position)
            }
        }
        likeDynamicLD.observeWithoutCache(viewLifecycleOwner) {
            profilePageViewModel.onDynamicLiked(it) { position ->
                profileAdapter.notifyItemChanged(position)
            }
        }
    }


    private fun goPlaymateDetail(detail: UserPlaymateSkill) {
        val act = activity ?: return
        Router.build(act, Playmate.Detail.PATH)
            .putExtra(Playmate.Detail.EXTRA_PLAYMATE_ID, detail.id)
            .putExtra(Playmate.Detail.EXTRA_PLAYMATE_NAME, detail.name)
            .start()
    }

    private fun likeDynamic(item: DynamicItemData, position: Int) {
        dynamicViewModel.like(item.dynamic).observe(viewLifecycleOwner) { rlt ->
            when (rlt) {
                is Rlt.Failed -> {
                    showFailedToast(rlt)
                }

                is Rlt.Success -> {
                    profileAdapter.notifyItemChanged(position)
                }
            }
        }
    }
}