package com.gh.gamecenter.gamecollection.detail.conversation

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import com.ethanhua.skeleton.Skeleton
import com.gh.common.util.CommentHelper
import com.gh.gamecenter.core.AppExecutor
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.R
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.baselist.LoadType
import com.gh.gamecenter.common.base.activity.ToolBarActivity
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.databinding.FragmentArticleDetailCommentBinding
import com.gh.gamecenter.entity.CommentEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.qa.comment.base.BaseCommentAdapter
import com.gh.gamecenter.qa.comment.base.BaseCommentFragment
import com.gh.gamecenter.qa.comment.base.BaseCommentViewModel
import com.gh.gamecenter.qa.article.detail.CommentItemData
import com.gh.gamecenter.qa.comment.CommentActivity
import com.gh.gamecenter.qa.comment.OnCommentOptionClickListener
import com.halo.assistant.HaloApp

class GameCollectionCommentConversationFragment :
    BaseCommentFragment<CommentItemData, GameCollectionCommentConversationViewModel>() {
    private lateinit var mViewModel: GameCollectionCommentConversationViewModel
    private lateinit var mBinding: FragmentArticleDetailCommentBinding
    private var mAdapterCommunity: GameCollectionCommentConversationAdapter? = null

    override fun getLayoutId() = 0

    override fun getInflatedLayout() =
        FragmentArticleDetailCommentBinding.inflate(
            LayoutInflater.from(requireContext()),
            null,
            false
        ).apply { mBinding = this }.root

    override fun onCreate(savedInstanceState: Bundle?) {
        mViewModel = provideListViewModel()
        super.onCreate(savedInstanceState)
        mViewModel.getComment()
        mViewModel.positionInOriginList = arguments?.getInt(EntranceConsts.KEY_POSITION)
            ?: -1
    }

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

    override fun provideListAdapter(): ListAdapter<*> {
        return mAdapterCommunity
            ?: GameCollectionCommentConversationAdapter(
                requireContext(),
                mViewModel,
                BaseCommentAdapter.AdapterType.SUB_COMMENT,
                mEntrance
            ) {
                if (it.user.id == UserManager.getInstance().userId) {
                    toast("不能回复自己")
                } else {
                    startCommentActivity(it)
                }
            }.apply {
                mAdapterCommunity = this
            }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        val commentCount = data?.getIntExtra(CommentActivity.COMMENT_COUNT, 0)
        debounceActionWithInterval(Activity.RESULT_OK) {
            if (commentCount != null && commentCount != 0) {
                mViewModel.commentDetail?.reply = commentCount
                mViewModel.commentCount = commentCount
                mViewModel.load(LoadType.REFRESH)
                mBinding.toolbarContainer.commentDialogCountTv.text =
                    "${mViewModel.commentDetail?.reply}条回复"
                SyncPageRepository.postSyncData(
                    SyncDataEntity(
                        mViewModel.commentId,
                        SyncFieldConstants.ARTICLE_COMMENT_REPLY_COUNT,
                        commentCount
                    )
                )
            }
        }
    }

    private fun initView() {
        mBinding.run {
            mSkeletonScreen = Skeleton.bind(skeletonView).shimmer(false)
                .load(R.layout.fragment_article_detail_comment_skeleton).show()

            inputContainer.bottomCommentIv.visibility = View.GONE
            inputContainer.bottomCommentTv.visibility = View.GONE
            inputContainer.bottomLikeIv.visibility = View.GONE
            inputContainer.bottomLikeTv.visibility = View.GONE
            inputContainer.bottomStarIv.visibility = View.GONE
            inputContainer.bottomStarTv.visibility = View.GONE

            inputContainer.replyTv.setRoundedColorBackground(R.color.background_space_2, 19F)
            inputContainer.replyTv.setDebouncedClickListener {
                mViewModel.commentDetail?.let { startCommentActivity(it) }
            }

            if (mViewModel.topCommentId.isNotBlank()) {
                initMenu(R.menu.menu_comment_detail)
                container.layoutParams =
                    (container.layoutParams as ViewGroup.MarginLayoutParams).apply {
                        topMargin = 0
                    }
                toolbarContainer.root.visibility = View.GONE
            } else {
                toolbarContainer.commentCloseIv.setOnClickListener { requireActivity().finish() }
            }
        }
    }

    override fun onMenuItemClick(menuItem: MenuItem?) {
        super.onMenuItemClick(menuItem)
        if (menuItem?.itemId == R.id.menu_more) {
            mViewModel.run {
                val actionMenuView = (requireActivity() as? ToolBarActivity)?.actionMenuView
                if (commentDetail != null && actionMenuView != null) {
                    CommentHelper.showGameCollectionCommentOption(
                        actionMenuView,
                        commentDetail!!,
                        mViewModel.gameCollectionId,
                        object : OnCommentOptionClickListener {
                            override fun onCommentOptionClick(entity: CommentEntity, option: String) {
                                when (option) {
                                    "删除评论" -> {
                                        DialogHelper.showDialog(
                                            requireContext(),
                                            "提示",
                                            "删除评论后，评论下所有的回复都将被删除",
                                            "删除",
                                            "取消",
                                            {
                                                mViewModel.deleteComment(commentDetail!!) {
                                                    requireActivity().finish()
                                                }
                                            },
                                            extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                                        )
                                    }
                                }
                            }
                        }
                    )
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun initObserver() {
        mViewModel.loadResultLiveData.observeNonNull(this) {
            when (it) {
                BaseCommentViewModel.LoadResult.SUCCESS -> {
                    mReuseNoConn?.visibility = View.GONE
                    mListLoading?.visibility = View.GONE

                    val showKeyboard =
                        arguments?.getBoolean(EntranceConsts.KEY_SHOW_KEYBOARD_IF_NEEDED)
                            ?: false
                    if (showKeyboard) {
                        mBinding.inputContainer.replyTv.performClick()
                    }

                    mBinding.inputContainer.replyTv.text =
                        "回复 @${mViewModel.commentDetail?.user?.name}"
                    mBinding.toolbarContainer.commentDialogCountTv.text =
                        "${mViewModel.commentDetail?.reply}条回复"
                    AppExecutor.uiExecutor.executeWithDelay(Runnable {
                        if ((mAdapterCommunity?.entityList?.size ?: 0) > 2) {
                            mListRv.smoothScrollToPosition(1)
                        }
                    }, 100)
                }
                else -> {
                    if (it == BaseCommentViewModel.LoadResult.DELETED) {
                        mReuseNoConn?.visibility = View.GONE
                        mReuseNoData?.visibility = View.VISIBLE
                        toast(R.string.content_delete_toast)
                    } else {
                        mReuseNoConn?.visibility = View.VISIBLE
                        mReuseNoData?.visibility = View.GONE
                        mReuseNoConn?.setOnClickListener {
                            mViewModel.getComment()
                            mReuseNoConn?.visibility = View.GONE
                            showSkeleton(true)
                        }
                    }

                    mListLoading?.visibility = View.GONE
                    mBinding.inputContainer.bottomContainer.visibility = View.GONE
                    mBinding.bottomShadowView.visibility = View.GONE
                    showSkeleton(false)
                }
            }
        }
    }

    override fun provideListViewModel(): GameCollectionCommentConversationViewModel {
        return viewModelProvider(
            GameCollectionCommentConversationViewModel.Factory(
                HaloApp.getInstance().application,
                arguments?.getString(CommentActivity.GAME_COLLECTION_ID) ?: "",
                arguments?.getString(EntranceConsts.KEY_COMMENT_ID) ?: "",
                arguments?.getString(EntranceConsts.KEY_TOP_COMMENT_ID) ?: ""
            )
        )
    }

    override fun onBackPressed(): Boolean {
        requireActivity().finish()
        return super.onBackPressed()
    }

    override fun onLoadDone() {
        showSkeleton(false)
        super.onLoadDone()
    }

    private fun startCommentActivity(comment: CommentEntity) {
        val intent = CommentActivity.getGameCollectionCommentReplyIntent(
            requireContext(),
            mViewModel.gameCollectionId,
            arguments?.getString(EntranceConsts.KEY_COMMENT_ID) ?: "",
            mViewModel.commentCount,
            comment
        )
        startActivityForResult(intent, CommentActivity.REQUEST_CODE)
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        if (::mBinding.isInitialized) {
            mBinding.container.background =
                R.drawable.game_detail_more_dialog_background.toDrawable(requireContext())
            mBinding.toolbarContainer.commentDialogCountTv.setTextColor(
                R.color.text_title.toColor(
                    requireContext()
                )
            )
            mBinding.inputContainer.run {
                bottomContainer.setBackgroundColor(R.color.background_white.toColor(requireContext()))
                replyTv.setRoundedColorBackground(R.color.background_space_2, 19F)
                replyTv.setTextColor(R.color.text_body.toColor(requireContext()))
                bottomShareTv.setTextColor(R.color.text_subtitle.toColor(requireContext()))
                bottomLikeTv.setTextColor(R.color.text_subtitle.toColor(requireContext()))
                bottomStarTv.setTextColor(R.color.text_subtitle.toColor(requireContext()))
                bottomCommentTv.setTextColor(R.color.text_subtitle.toColor(requireContext()))
            }
            mBinding.fixedTopFilterView.run {
                filterView.setBackgroundColor(R.color.background_white.toColor(requireContext()))
                divider.setBackgroundColor(R.color.divider.toColor(requireContext()))
                commentHintTv.setTextColor(R.color.text_title.toColor(requireContext()))
                commentHintCountTv.setTextColor(R.color.text_subtitleDesc.toColor(requireContext()))
                orderSfv.run {
                    setContainerBackground(R.drawable.button_round_f5f5f5.toDrawable(requireContext()))
                    setIndicatorBackground(
                        R.drawable.bg_game_collection_sfv_indicator.toDrawable(
                            requireContext()
                        )
                    )
                    setTextColor(
                        ContextCompat.getColorStateList(
                            requireContext(),
                            R.color.game_collection_rg_button_selector
                        )
                    )
                }
            }
        }
    }
}