package com.gh.gamecenter.qa.video.detail.comment

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.baselist.LazyListFragment
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.baselist.LoadType
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.mvvm.Status
import com.gh.gamecenter.common.syncpage.SyncDataEntity
import com.gh.gamecenter.common.syncpage.SyncFieldConstants
import com.gh.gamecenter.common.syncpage.SyncPageRepository
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.CustomDividerItemDecoration
import com.gh.gamecenter.common.view.SegmentedFilterView
import com.gh.gamecenter.databinding.FragmentVideoCommentListBinding
import com.gh.gamecenter.feature.entity.ForumVideoEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.qa.article.detail.CommentItemData
import com.gh.gamecenter.qa.comment.CommentActivity
import com.gh.gamecenter.qa.comment.base.BaseCommentViewModel
import com.gh.gamecenter.qa.video.detail.ForumVideoDetailViewModel

class VideoCommentFragment : LazyListFragment<CommentItemData, VideoCommentViewModel>() {
    private lateinit var mBinding: FragmentVideoCommentListBinding
    private lateinit var mVideoDetailViewModel: ForumVideoDetailViewModel
    private var mAdapter: VideoCommentAdapter? = null
    private var mVideoId = ""
    private var mBbsId = ""

    override fun provideListAdapter(): ListAdapter<*> {
        return mAdapter ?: VideoCommentAdapter(requireContext(), mListViewModel, mEntrance).apply {
            mAdapter = this
        }
    }

    override fun getRealLayoutId(): Int = R.layout.fragment_video_comment_list

    override fun getItemDecoration(): RecyclerView.ItemDecoration {
        val insetDivider =
            ContextCompat.getDrawable(requireContext(), com.gh.gamecenter.common.R.drawable.divider_item_line_space_16)
        val itemDecoration =
            CustomDividerItemDecoration(requireContext(), notDecorateTheLastItem = true)
        itemDecoration.setDrawable(insetDivider!!)
        mItemDecoration = itemDecoration
        return itemDecoration
    }

    override fun provideListViewModel(): VideoCommentViewModel {
        return viewModelProvider(
            VideoCommentViewModel.Factory(
                mVideoId,
                mBbsId,
                arguments?.getString(EntranceConsts.KEY_TOP_COMMENT_ID) ?: ""
            )
        )
    }

    override fun onRealLayoutInflated(inflatedView: View) {
        mBinding = FragmentVideoCommentListBinding.bind(inflatedView)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        mVideoId = arguments?.getString(EntranceConsts.KEY_VIDEO_ID) ?: ""
        mBbsId = arguments?.getString(EntranceConsts.KEY_BBS_ID) ?: ""
        super.onCreate(savedInstanceState)
    }

    override fun onFragmentFirstVisible() {
        mVideoDetailViewModel = viewModelProviderFromParent()
        super.onFragmentFirstVisible()
        mListRefresh?.isEnabled = false
        mBinding.orderSfv.setItemList(listOf("正序", "倒序"), 0)
        mBinding.orderSfv.setOnCheckedCallback(object : SegmentedFilterView.OnCheckedCallback {
            override fun onItemCheck(position: Int) {
                when (position) {
                    0 -> {
                        mListViewModel.changeSort(BaseCommentViewModel.SortType.OLDEST)
                        updateSortType()
                    }
                    1 -> {
                        mListViewModel.changeSort(BaseCommentViewModel.SortType.LATEST)
                        updateSortType()
                    }
                }
            }
        })
        observeData()
    }

    private fun observeData() {
        mVideoDetailViewModel.detailLiveData.observeNonNull(this) {
            if (it.status == Status.SUCCESS) {
                mListViewModel.videoDetail = it.data as ForumVideoEntity
                mBinding.allCommentCountTv.text =
                    mListViewModel.videoDetail?.count?.comment.toString()
                onRefresh()
            }
        }
        mVideoDetailViewModel.updateDetailLiveData.observeNonNull(this) {
            mListViewModel.videoDetail = it
            mBinding.allCommentCountTv.text = it.count.comment.toString()
        }
        mListViewModel.deleteCommentLiveData.observeNonNull(this) {
            mBinding.allCommentCountTv.text = mListViewModel.videoDetail?.count?.comment.toString()
            mVideoDetailViewModel.updateDetailLiveData.postValue(mListViewModel.videoDetail)
        }
    }

    private fun updateSortType() {
        mBinding.run {
//            val isLatestSelected =
//                mListViewModel.currentSortType == BaseCommentViewModel.SortType.LATEST
//            val selectedTextView = if (isLatestSelected) filterLatestTv else filterOldestTv
//            val unselectedTextView = if (!isLatestSelected) filterLatestTv else filterOldestTv

//            selectedTextView.setTextColor(R.color.theme_font.toColor())
//            unselectedTextView.setTextColor(R.color.text_subtitleDesc.toColor())
        }
    }

    fun startCommentActivity() {
        if (!isSupportVisible) return
        clickToastByStatus(mListViewModel.videoDetail?.status ?: "") {
            mListViewModel.videoDetail?.let {
                val intent = CommentActivity.getVideoCommentIntent(
                    requireContext(),
                    it.id,
                    it.count.comment,
                    it.user.id == UserManager.getInstance().userId,
                    true, true, false
                )
                startActivityForResult(intent, CommentActivity.REQUEST_CODE)
                val bbsType = if (mListViewModel.videoDetail?.type == "game_bbs") "游戏论坛" else "综合论坛"
                NewLogUtils.logCommentClick(
                    "click_comment_area_comment_input_box", mListViewModel.videoDetail?.user?.id
                        ?: "", "视频帖", mListViewModel.videoDetail?.id
                        ?: "", mListViewModel.videoDetail?.bbs?.id ?: "", bbsType
                )
            }
        }
    }

    override fun addSyncPageObserver(): Boolean = true

    override fun provideSyncAdapter() = mAdapter

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null || resultCode != Activity.RESULT_OK) return
        if (requestCode == CommentActivity.REQUEST_CODE) {
            val commentCount = data.getIntExtra(CommentActivity.COMMENT_COUNT, 0)
            val commentId = data.getStringExtra(EntranceConsts.KEY_COMMENT_ID)
            if (commentCount != 0) {
                mListViewModel.videoDetail?.let {
                    it.count.comment = commentCount
                    mBinding.allCommentCountTv.text = it.count.comment.toString()
                    mVideoDetailViewModel.updateDetailLiveData.postValue(it)
                    SyncPageRepository.postSyncData(
                        SyncDataEntity(
                            mVideoId,
                            SyncFieldConstants.ARTICLE_COMMENT_COUNT,
                            it.count.comment,
                            checkFieldEntity = true
                        )
                    )
                }
            }
            if (!commentId.isNullOrEmpty()) {
                mListViewModel.getSingleCommentDetail(commentId)
            } else {
                mListViewModel.load(LoadType.REFRESH)
            }
        }
    }

    override fun onLoadRefresh() {
        showSkeleton(true)
    }

    override fun onLoadEmpty() {
        showSkeleton(false)
        if (mReuseNoConn != null) mReuseNoConn!!.visibility = View.GONE
        if (mReuseNoData != null) mReuseNoData!!.visibility = View.GONE
        if (mListLoading != null) mListLoading!!.visibility = View.GONE

        mListRv?.visibility = View.VISIBLE
        hideRefreshingLayout()
    }

    override fun onLoadDone() {
        mReuseNoConn?.visibility = View.GONE
        mReuseNoData?.visibility = View.GONE
        mListLoading?.visibility = View.GONE

        mListRv?.visibility = View.VISIBLE
        hideRefreshingLayout()
        mListRv?.postDelayed({
            mListRv?.scrollToPosition(0)
        }, 50)

        mListRv?.postDelayed({
            if (provideListAdapter().itemCount < theNumberNeededToFillAScreen()) {
                autoLoadMore()
            }
        }, autoLoadMoreDelay.toLong())
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        if (::mBinding.isInitialized) {
            mBinding.orderSfv.run {
                setContainerBackground(com.gh.gamecenter.common.R.drawable.button_round_f5f5f5.toDrawable(requireContext()))
                setIndicatorBackground(
                    R.drawable.bg_game_collection_sfv_indicator.toDrawable(
                        requireContext()
                    )
                )
                setTextColor(
                    com.gh.gamecenter.common.R.color.text_secondary.toColor(requireContext()),
                    com.gh.gamecenter.common.R.color.text_tertiary.toColor(requireContext())
                )
            }
        }
    }
}