package com.gh.gamecenter.forum.home.follow.fragment

import android.graphics.Canvas
import android.graphics.Paint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.children
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.DirectUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.fragment.BaseFragment
import com.gh.gamecenter.common.base.fragment.ToolbarFragment
import com.gh.gamecenter.common.baselist.LoadStatus
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.databinding.FragmentFollowDynamicListBinding
import com.gh.gamecenter.feature.entity.CommentEntity
import com.gh.gamecenter.feature.entity.ForumVideoEntity
import com.gh.gamecenter.forum.detail.ForumDetailActivity
import com.gh.gamecenter.forum.home.follow.FollowActivityResultLauncher
import com.gh.gamecenter.forum.home.follow.FollowDynamicBbsItem
import com.gh.gamecenter.forum.home.follow.FollowDynamicPersonalItem
import com.gh.gamecenter.forum.home.follow.adapter.FollowDynamicAdapter
import com.gh.gamecenter.forum.home.follow.viewmodel.FollowDynamicListViewModel
import com.gh.gamecenter.forum.home.follow.viewmodel.FollowDynamicViewModel
import com.gh.gamecenter.livedata.EventObserver
import com.gh.gamecenter.qa.BbsType
import com.gh.gamecenter.qa.entity.ArticleDetailEntity
import com.gh.gamecenter.qa.entity.QuestionsDetailEntity

class FollowDynamicListFragment : BaseFragment<Unit>() {

    private var userId: String = ""
    private var bbsId: String = ""
    private var bbsType: String = ""

    private val paint by lazy {
        Paint().apply {
            color = com.gh.gamecenter.common.R.color.ui_divider.toColor(requireContext())
            strokeWidth = 0.5F.dip2px().toFloat()
        }
    }

    private val viewModel by viewModels<FollowDynamicListViewModel>()

    private val followDynamicViewModel by activityViewModels<FollowDynamicViewModel>()

    private val binding by lazy {
        FragmentFollowDynamicListBinding.inflate(layoutInflater, null, false)
    }

    private val adapter by lazy {
        FollowDynamicAdapter(requireContext(), viewModel)
    }

    private lateinit var launcher: FollowActivityResultLauncher

    override fun getInflatedLayout(): View {
        return binding.root
    }

    override fun getLayoutId(): Int = R.layout.fragment_follow_dynamic_list

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        userId = arguments?.getString(KEY_USER_ID) ?: ""
        bbsId = arguments?.getString(KEY_BBS_ID) ?: ""
        bbsType = arguments?.getString(KEY_BBS_TYPE) ?: ""
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initView()

        with(viewModel) {
            loadStatus.observe(viewLifecycleOwner) { (loadStatus, isPullRefresh) ->
                if (isPullRefresh) {
                    if (loadStatus != LoadStatus.INIT_LOADING) {
                        binding.srlRefresh.isRefreshing = false
                    }
                } else {
                    binding.reuseLoading.root.goneIf(loadStatus != LoadStatus.INIT_LOADING)
                    binding.reuseNoData.root.goneIf(loadStatus != LoadStatus.INIT_EMPTY)
                    binding.reuseNoConnection.root.goneIf(loadStatus != LoadStatus.LIST_FAILED)
                    binding.srlRefresh.isEnabled =
                        !(loadStatus == LoadStatus.INIT_FAILED || loadStatus == LoadStatus.INIT_LOADING)
                }
                adapter.setLoadStatus(loadStatus)

            }

            dataList.observe(viewLifecycleOwner) {
                adapter.submitList(it)
            }

            personDetailDestination.observe(viewLifecycleOwner, EventObserver { (personalEntity, position) ->
                launcher.onPersonItemClick(position, personalEntity)
            })

            bbsDetailDestination.observe(viewLifecycleOwner, EventObserver { (position, answer) ->
                launcher.onBbsItemClick(position, answer)
            })

        }

        followDynamicViewModel.isStartLoadAction.observe(viewLifecycleOwner, Observer {
            if (it) {
                viewModel.loadFirst(userId, bbsId, false)
            }
        })

        binding.tvTitle.text = if (userId.isNotBlank()) {
            getString(R.string.follow_detail_person_updates)
        } else {
            if (bbsType == BbsType.OFFICIAL_BBS.value) {
                getString(R.string.follow_detail_bbs_updates)
            } else {
                getString(R.string.follow_detail_game_updates)
            }

        }

        binding.tvRight.text =
            if (userId.isNotBlank()) {
                getString(R.string.user_home_page)
            } else {
                getString(R.string.go_to_forum)
            }

        binding.tvRight.setOnClickListener {
            if (userId.isNotBlank()) {
                DirectUtils.directToHomeActivity(requireContext(), userId)
            } else {
                startActivity(ForumDetailActivity.getIntent(requireContext(), bbsId, ""))
            }
        }
    }

    private fun initView() {
        launcher = FollowActivityResultLauncher(requireActivity().activityResultRegistry,
            object : FollowActivityResultLauncher.OnResultListener {
                override fun onArticleDetailResult(position: Int, articleDetailEntity: ArticleDetailEntity) {
                    val item = adapter.currentList.getOrNull(position) ?: return
                    if (item is FollowDynamicPersonalItem) {
                        item.data.apply {
                            val newCount = count
                            newCount.vote = articleDetailEntity.count.vote
                            newCount.comment = articleDetailEntity.count.comment
                            count = newCount
                            title = articleDetailEntity.title
                            brief = articleDetailEntity.content.removeVideoContent().removeInsertedContent()
                                .clearHtmlFormatCompletely()
                            me.isCommunityArticleVote = articleDetailEntity.me.isCommunityArticleVote
                        }
                    }
                    if (item is FollowDynamicBbsItem) {
                        item.data.apply {
                            val newCount = count
                            newCount.vote = articleDetailEntity.count.vote
                            newCount.comment = articleDetailEntity.count.comment
                            count = newCount
                            title = articleDetailEntity.title
                            brief = articleDetailEntity.content.removeVideoContent().removeInsertedContent()
                                .clearHtmlFormatCompletely()
                            me.isCommunityArticleVote = articleDetailEntity.me.isCommunityArticleVote
                        }
                    }

                    adapter.notifyItemChanged(position)
                }

                override fun onCommentResult(position: Int, commentEntity: CommentEntity) {
                    val item = adapter.currentList.getOrNull(position) ?: return
                    if (item is FollowDynamicPersonalItem) {
                        item.data.apply {
                            val newCount = count
                            newCount.vote = commentEntity.vote
                            newCount.comment = commentEntity.reply
                            count = newCount
                            brief = commentEntity.content ?: ""
                            me.isAnswerVoted = commentEntity.me?.isCommentVoted ?: false
                        }
                    }
                    if (item is FollowDynamicBbsItem) {
                        item.data.apply {
                            val newCount = count
                            newCount.vote = commentEntity.vote
                            newCount.comment = commentEntity.reply
                            count = newCount
                            brief = commentEntity.content ?: ""
                            me.isAnswerVoted = commentEntity.me?.isCommentVoted ?: false
                        }
                    }

                    adapter.notifyItemChanged(position)
                }

                override fun onQuestionsDetailResult(position: Int, questionsDetailEntity: QuestionsDetailEntity) {
                    val item = adapter.currentList.getOrNull(position) ?: return
                    if (item is FollowDynamicPersonalItem) {
                        item.data.apply {
                            val newCount = count
                            newCount.answer = questionsDetailEntity.count.answer - count.reply
                            count = newCount
                            title = questionsDetailEntity.title ?: ""
                        }
                    }
                    if (item is FollowDynamicBbsItem) {
                        item.data.apply {
                            val newCount = count
                            newCount.answer = questionsDetailEntity.count.answer - count.reply
                            count = newCount
                            title = questionsDetailEntity.title ?: ""
                        }
                    }
                    adapter.notifyItemChanged(position)
                }

                override fun onForumVideoResult(position: Int, forumVideoEntity: ForumVideoEntity) {
                    val item = adapter.currentList.getOrNull(position) ?: return
                    if (item is FollowDynamicPersonalItem) {
                        item.data.apply {
                            val newCount = count
                            newCount.vote = forumVideoEntity.count.vote
                            newCount.comment = forumVideoEntity.count.comment
                            count = newCount
                            des = forumVideoEntity.des
                            title = forumVideoEntity.title
                            me.isVoted = forumVideoEntity.me.isVoted
                        }
                    }
                    if (item is FollowDynamicBbsItem) {
                        item.data.apply {
                            val newCount = count
                            newCount.vote = forumVideoEntity.count.vote
                            newCount.comment = forumVideoEntity.count.comment
                            count = newCount
                            des = forumVideoEntity.des
                            title = forumVideoEntity.title
                            me.isVoted = forumVideoEntity.me.isVoted
                        }
                    }
                    adapter.notifyItemChanged(position)
                }

            })
        viewLifecycleOwner.lifecycle.addObserver(launcher)

        binding.rvDynamic.layoutManager = LinearLayoutManager(requireContext())
        binding.rvDynamic.itemAnimator = null
        binding.rvDynamic.addItemDecoration(FollowItemDecoration(paint))
        binding.rvDynamic.adapter = adapter

        binding.srlRefresh.setOnRefreshListener {
            viewModel.loadFirst(userId, bbsId, true)
        }

        binding.ivClose.setOnClickListener {
            followDynamicViewModel.finish()
        }
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        context?.let {
            binding.vHeaderBackground.background = com.gh.gamecenter.common.R.drawable.background_shape_white_radius_8_top_only.toDrawable(it)
        }
        binding.rvDynamic.tryToClearRecycler()
        binding.rvDynamic.recycledViewPool.clear()
        adapter.notifyItemRangeChanged(0, adapter.itemCount)
        paint.color = com.gh.gamecenter.common.R.color.ui_divider.toColor(requireContext())
    }

    private class FollowItemDecoration(
        private val paint: Paint
    ) : RecyclerView.ItemDecoration() {
        override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
            super.onDrawOver(c, parent, state)
            parent.children.forEach { child ->
                val bottom = child.bottom
                c.drawLine(
                    16F.dip2px().toFloat(),
                    bottom.toFloat(),
                    (child.width - 16F.dip2px()).toFloat(),
                    bottom.toFloat(),
                    paint
                )
            }
        }

    }

    companion object {

        private const val KEY_USER_ID = "key_user_id"
        private const val KEY_BBS_ID = "key_bbs_id"
        private const val KEY_BBS_TYPE = "key_bbs_type"

        fun newInstance(userId: String, bbsId: String, bbsType: String): FollowDynamicListFragment {
            val fragment = FollowDynamicListFragment()
            val bundle = Bundle().apply {
                putString(KEY_USER_ID, userId)
                putString(KEY_BBS_ID, bbsId)
                putString(KEY_BBS_TYPE, bbsType)
            }
            fragment.arguments = bundle
            return fragment
        }
    }

}