package com.gh.gamecenter.gamedetail.dialog

import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.gh.gamecenter.BuildConfig
import com.gh.gamecenter.common.base.fragment.BaseBottomDialogFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.viewModelProviderFromParent
import com.gh.gamecenter.databinding.DialogGameDetailRecyclerViewBinding
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.gamedetail.GameDetailViewModel
import com.gh.gamecenter.gamedetail.detail.viewholder.GameDetailInfoItemViewHolder.Companion.normalTypeNameMap
import com.gh.gamecenter.gamedetail.entity.GameDetailInfo
import com.halo.assistant.HaloApp
import com.lightgame.utils.AppManager

class GameInfoDialogFragment : BaseBottomDialogFragment<DialogGameDetailRecyclerViewBinding>() {
    private var gameEntity: GameEntity? = null
    private var gameDetailInfo: GameDetailInfo? = null
    private val viewModel: GameDetailViewModel by lazy {
        val factory = GameDetailViewModel.Factory(
            HaloApp.getInstance().application,
            gameEntity?.id,
            gameEntity
        )
        viewModelProviderFromParent(factory, gameEntity?.id ?: "")
    }
    private val adapter by lazy {
        val normalTypeKeys = normalTypeNameMap.keys
        val infoList = gameDetailInfo?.fields?.filter { normalTypeKeys.contains(it.name) }?.sortedBy { it.order } ?: arrayListOf()
        GameInfoAdapter(requireContext(), gameDetailInfo, infoList, viewModel)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        gameEntity = arguments?.getParcelable(EntranceConsts.KEY_GAME)
        gameDetailInfo = arguments?.getParcelable(KEY_GAME_DETAIL_INFO)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mBinding.titleTv.text = gameDetailInfo?.name
        mBinding.closeIv.setOnClickListener {
            dismissAllowingStateLoss()
        }
        mBinding.recyclerView.run {
            setPadding(16F.dip2px(), 16F.dip2px(), 16F.dip2px(), 0)
            layoutManager = LinearLayoutManager(requireContext())
            adapter = this@GameInfoDialogFragment.adapter
            (itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false
        }
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        adapter.notifyItemRangeChanged(0, adapter.itemCount)
    }

    companion object {
        const val KEY_GAME_DETAIL_INFO = "game_detail_info"

        @JvmStatic
        fun show(context: Context?, gameEntity: GameEntity?, data: GameDetailInfo) {
            val fragmentActivity: FragmentActivity = if (context is FragmentActivity) {
                context
            } else if (BuildConfig.DEBUG) {
                throw IllegalStateException("GameInfoDialogFragment context must be FragmentActivity")
            } else {
                val currentActivity = AppManager.getInstance().currentActivity()
                if (currentActivity is FragmentActivity) {
                    currentActivity
                } else {
                    throw IllegalStateException("current activity context must be FragmentActivity")
                }
            }

            // 防止重复弹出
            if (hasDialogInCurrentActivity(fragmentActivity)) return

            val dialogFragment = GameInfoDialogFragment()
            dialogFragment.arguments = bundleOf(
                EntranceConsts.KEY_GAME to gameEntity,
                KEY_GAME_DETAIL_INFO to data
            )
            dialogFragment.show(fragmentActivity.supportFragmentManager, GameInfoDialogFragment::class.java.name)
        }

        private fun hasDialogInCurrentActivity(fragmentActivity: FragmentActivity): Boolean {
            val fragments: List<Fragment> = fragmentActivity.supportFragmentManager.fragments
            fragments.forEach { fragment ->
                if (fragment is GameInfoDialogFragment) return true
            }
            return false
        }
    }
}