package com.gh.gamecenter.personalhome.home.game

import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import com.gh.gamecenter.common.constant.EntranceConsts.*
import com.gh.gamecenter.R
import com.gh.gamecenter.collection.GamesCollectionFragment
import com.gh.gamecenter.databinding.FragmentUserGameBinding
import com.gh.gamecenter.entity.PersonalEntity
import com.gh.gamecenter.common.base.fragment.ToolbarFragment
import com.gh.gamecenter.common.utils.*

class UserGameFragment : ToolbarFragment() {

    private var mBinding: FragmentUserGameBinding? = null
    private var mViewModel: UserGameViewModel? = null
    private var mGamesCollectionFragment: GamesCollectionFragment? = null
    private var mPlayedGameFragment: UserPlayedGameFragment? = null
    private var mCommentFragment: UserCommentHistoryFragment? = null
    private var mUserId: String = ""
    private var mFilter: String = "全部"
    private var mCount = PersonalEntity.Count()
    private var mCurrentType = TYPE_GAME_COLLECTION

    override fun getLayoutId() = 0

    override fun getInflatedLayout() = FragmentUserGameBinding.inflate(layoutInflater).apply { mBinding = this }.root

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mUserId = arguments?.getString(KEY_USER_ID, "") ?: ""
        mCount = arguments?.getParcelable(COUNT) ?: PersonalEntity.Count()
        mCurrentType = arguments?.getInt(TYPE) ?: TYPE_GAME_COLLECTION
        mViewModel = viewModelProvider(UserGameViewModel.Factory(mUserId))
        updateTypeView(mCurrentType)
        changeType(mCurrentType)
    }

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

        mViewModel?.playedGameCount?.observeNonNull(viewLifecycleOwner) {
            mBinding?.gameType?.text = "玩过 $it"
        }

        mBinding?.run {
            gameCollectionType.text = "游戏单 ${mCount.gameList}"
            commentType.text = "评价 ${mCount.gameComment}"

            val typePairList = arrayListOf(
                Pair(TYPE_GAME_COLLECTION, gameCollectionType),
                Pair(TYPE_PLAYED_GAME, gameType),
                Pair(TYPE_COMMENT, commentType)
            )

            typePairList.forEach { pair ->
                pair.second.setOnClickListener {
                    if (mCurrentType != pair.first) {
                        mCurrentType = pair.first
                        updateTypeView(pair.first)
                        changeType(pair.first)
                    }
                }
            }

            commentSubType.setOnClickListener {
                showCommentTypePopupWindow()
            }
        }
    }

    private fun updateTypeView(type: Int) {
        mBinding?.run {
            when (type) {
                TYPE_GAME_COLLECTION -> {
                    commentSubType.visibility = View.GONE
                    arrowIv.visibility = View.GONE
                    gameCollectionType.background = R.drawable.bg_user_game_type_selected.toDrawable(requireContext())
                    gameCollectionType.setTextColor(R.color.theme_font.toColor(requireContext()))
                    gameType.background = R.drawable.bg_user_game_type_unselect.toDrawable(requireContext())
                    gameType.setTextColor(R.color.text_subtitleDesc.toColor(requireContext()))
                    commentType.background = R.drawable.bg_user_game_type_unselect.toDrawable(requireContext())
                    commentType.setTextColor(R.color.text_subtitleDesc.toColor(requireContext()))
                }
                TYPE_PLAYED_GAME -> {
                    commentSubType.visibility = View.GONE
                    arrowIv.visibility = View.GONE
                    gameCollectionType.background = R.drawable.bg_user_game_type_unselect.toDrawable(requireContext())
                    gameCollectionType.setTextColor(R.color.text_subtitleDesc.toColor(requireContext()))
                    gameType.background = R.drawable.bg_user_game_type_selected.toDrawable(requireContext())
                    gameType.setTextColor(R.color.theme_font.toColor(requireContext()))
                    commentType.background = R.drawable.bg_user_game_type_unselect.toDrawable(requireContext())
                    commentType.setTextColor(R.color.text_subtitleDesc.toColor(requireContext()))
                }
                else -> {
                    commentSubType.visibility = View.VISIBLE
                    arrowIv.visibility = View.VISIBLE
                    gameCollectionType.background = R.drawable.bg_user_game_type_unselect.toDrawable(requireContext())
                    gameCollectionType.setTextColor(R.color.text_subtitleDesc.toColor(requireContext()))
                    gameType.background = R.drawable.bg_user_game_type_unselect.toDrawable(requireContext())
                    gameType.setTextColor(R.color.text_subtitleDesc.toColor(requireContext()))
                    commentType.background = R.drawable.bg_user_game_type_selected.toDrawable(requireContext())
                    commentType.setTextColor(R.color.theme_font.toColor(requireContext()))
                }
            }
        }
    }

    private fun changeType(type: Int) {
        when (type) {
            TYPE_GAME_COLLECTION -> {
                mGamesCollectionFragment =
                    childFragmentManager.findFragmentByTag(UserPlayedGameFragment::class.java.name) as? GamesCollectionFragment
                        ?: GamesCollectionFragment()
                mGamesCollectionFragment?.arguments =
                    bundleOf(KEY_USER_ID to mUserId, KEY_TYPE to GamesCollectionFragment.TYPE_USER)
                childFragmentManager.beginTransaction()
                    .replace(
                        R.id.contentContainer,
                        mGamesCollectionFragment!!,
                        GamesCollectionFragment::class.java.name
                    )
                    .commitAllowingStateLoss()
            }
            TYPE_PLAYED_GAME -> {
                mPlayedGameFragment =
                    childFragmentManager.findFragmentByTag(UserPlayedGameFragment::class.java.name) as? UserPlayedGameFragment
                        ?: UserPlayedGameFragment()
                mPlayedGameFragment?.arguments = bundleOf(KEY_USER_ID to mUserId)
                childFragmentManager.beginTransaction()
                    .replace(R.id.contentContainer, mPlayedGameFragment!!, UserPlayedGameFragment::class.java.name)
                    .commitAllowingStateLoss()
            }
            else -> {
                mCommentFragment =
                    childFragmentManager.findFragmentByTag(UserCommentHistoryFragment::class.java.name) as? UserCommentHistoryFragment
                        ?: UserCommentHistoryFragment()
                mCommentFragment?.arguments = bundleOf(KEY_USER_ID to mUserId)
                childFragmentManager.beginTransaction()
                    .replace(R.id.contentContainer, mCommentFragment!!, UserCommentHistoryFragment::class.java.name)
                    .commitAllowingStateLoss()
            }
        }
    }

    private fun showCommentTypePopupWindow() {
        mBinding?.run {
            val contentList = arrayListOf("全部", "精华", "安利墙")

            val inflater = LayoutInflater.from(requireContext())
            val layout = inflater.inflate(R.layout.layout_popup_container, null)
            val popupWindow = PopupWindow(
                layout,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
            popupWindow.apply {
                setBackgroundDrawable(ColorDrawable(0))
                isTouchable = true
                isFocusable = true
                isOutsideTouchable = true
            }

            val container = layout.findViewById<LinearLayout>(R.id.container)
            for (text in contentList) {
                val item = inflater.inflate(R.layout.layout_popup_option_item, container, false)
                if (mFilter == text) {
                    (item as TextView).setTextColor(ContextCompat.getColor(requireContext(), R.color.theme_font))
                } else {
                    (item as TextView).setTextColor(ContextCompat.getColor(requireContext(), R.color.text_subtitle))
                }
                container.addView(item)

                val hitText = item.findViewById<TextView>(R.id.hint_text)
                hitText.text = text

                item.setOnClickListener {
                    mFilter = text
                    commentSubType.text = text
                    changeCommentType(text)
                    popupWindow.dismiss()
                }
            }
            popupWindow.setOnDismissListener {
                arrowIv.rotation = 0f
            }
            arrowIv.rotation = 180f
            popupWindow.showAutoOrientation(commentSubType)
        }
    }

    private fun changeCommentType(text: String) {
        mCommentFragment?.changeType(text)
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        updateTypeView(mCurrentType)
    }

    companion object {
        private const val TYPE_GAME_COLLECTION = 100
        private const val TYPE_PLAYED_GAME = 101
        private const val TYPE_COMMENT = 102
        const val COUNT = "count"
        const val TYPE = "type"

        fun getInstance(userId: String, count: PersonalEntity.Count, gameType: String = "game_collection"): UserGameFragment {
            val type = when (gameType) {
                "game_collection" -> 100
                "played_game" -> 101
                "comment" -> 102
                else -> 100
            }

            return UserGameFragment().apply {
                with(
                    bundleOf(
                        COUNT to count,
                        TYPE to type,
                        KEY_USER_ID to userId
                    )
                )
            }
        }
    }
}