package com.gh.gamecenter.gamedetail.cloudarchive

import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.core.os.bundleOf
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.cloudarchive.CloudArchiveManagerActivity
import com.gh.gamecenter.common.base.GlobalActivityManager
import com.gh.gamecenter.common.base.fragment.LazyFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.json.json
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.databinding.FragmentCloudArchiveAlBinding
import com.gh.gamecenter.databinding.FragmentCloudArchiveBinding
import com.gh.gamecenter.feature.entity.GameEntity

class CloudArchiveFragment : LazyFragment() {

    private var mUseAlternativeLayout = false
    private var mGameEntity: GameEntity? = null
    private var mBinding: FragmentCloudArchiveBinding? = null
    private var mAlternativeBinding: FragmentCloudArchiveAlBinding? = null
    private var mSearchFragment: CloudArchiveListFragment? = null
    private var mNormalFragment: CloudArchiveListFragment? = null
    private var mIsSearch = false
    private var mOrderList =
        listOf(CloudArchiveListViewModel.SortType.NEWEST, CloudArchiveListViewModel.SortType.HOTTEST)

    private val searchBarBinding
        get() = if (mUseAlternativeLayout) mAlternativeBinding?.searchBar else mBinding?.searchBar

    private val orderSfv
        get() = if (mUseAlternativeLayout) mAlternativeBinding?.orderSfv else mBinding?.orderSfv

    private val archiveManageTv
        get() = if (mUseAlternativeLayout) mAlternativeBinding?.archiveManageTv else mBinding?.archiveManageTv

    override fun onCreate(savedInstanceState: Bundle?) {
        mUseAlternativeLayout = arguments?.getBoolean(EntranceConsts.KEY_USE_ALTERNATIVE_LAYOUT) ?: false
        super.onCreate(savedInstanceState)
    }

    override fun getRealLayoutId() =
        if (mUseAlternativeLayout) R.layout.fragment_cloud_archive_al else R.layout.fragment_cloud_archive

    override fun onRealLayoutInflated(inflatedView: View) {
        if (mUseAlternativeLayout) {
            mAlternativeBinding = FragmentCloudArchiveAlBinding.bind(inflatedView)
        } else {
            mBinding = FragmentCloudArchiveBinding.bind(inflatedView)
        }
    }

    override fun onFragmentFirstVisible() {
        mGameEntity = arguments?.getParcelable(EntranceConsts.KEY_GAME_ENTITY)
        super.onFragmentFirstVisible()
        if (mUseAlternativeLayout) {
            requireActivity().updateStatusBarColor(com.gh.gamecenter.common.R.color.ui_surface, com.gh.gamecenter.common.R.color.ui_surface)
        }
        changeContentFragment()

        SensorsBridge.trackEvent("CloudSavePageView", json {
            "game_id" to mGameEntity?.id
            "game_name" to mGameEntity?.name
            "last_page_name" to GlobalActivityManager.getLastPageEntity().pageName
            "last_page_id" to GlobalActivityManager.getLastPageEntity().pageId
        })
    }

    override fun inflateRealView() {
        super.inflateRealView()
        mAlternativeBinding?.run {
            reuseToolbar.backBtn.setOnClickListener {
                requireActivity().onBackPressed()
            }
            reuseToolbar.normalTitle.run {
                text = "${mGameEntity?.name}-云存档"
                marqueeOnce()
            }
        }
        orderSfv?.run {
            setItemList(mOrderList.map { it.value }, 1)
            setOnCheckedCallback {
                if (mIsSearch) {
                    mSearchFragment?.updateSortType(mOrderList[it])
                } else {
                    mNormalFragment?.updateSortType(mOrderList[it])
                }
            }
        }
        searchBarBinding?.run {
            etSearch.hint = R.string.game_detail_cloud_archive_search_hint.toResString()
            tvBack.setOnClickListener {
                changeSearchStatus(false)
                etSearch.setText("")
            }
            etSearch.setOnEditorActionListener { _, actionId, _ ->
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    tvSearch.performClick()
                }
                false
            }
            tvSearch.setOnClickListener {
                val keyWord = etSearch.text.toString().trim { it <= ' ' }
                if (keyWord.isBlank()) {
                    toast(R.string.search_hint)
                } else {
                    changeSearchStatus(true)
                }
            }
        }
        archiveManageTv?.setOnClickListener {
            startActivity(
                CloudArchiveManagerActivity.getIntent(
                    requireContext(),
                    mGameEntity ?: GameEntity(),
                    arguments?.getString(EntranceConsts.KEY_ARCHIVE_CONFIG_URL) ?: "",
                    "游戏详情页"
                )
            )
        }
    }

    private fun changeContentFragment() {
        if (mIsSearch) {
            mSearchFragment =
                childFragmentManager.findFragmentByTag("${CloudArchiveListFragment::class.java.name}_search")
                        as? CloudArchiveListFragment ?: CloudArchiveListFragment()
            alterFragment(mSearchFragment!!)
        } else {
            mNormalFragment =
                childFragmentManager.findFragmentByTag("${CloudArchiveListFragment::class.java.name}_normal")
                        as? CloudArchiveListFragment ?: CloudArchiveListFragment()
            alterFragment(mNormalFragment!!)
        }
    }

    private fun alterFragment(fragment: CloudArchiveListFragment) {
        val bundle = bundleOf(
            EntranceConsts.KEY_GAME to (mGameEntity ?: GameEntity()),
            EntranceConsts.KEY_ARCHIVE_CONFIG_URL to arguments?.getString(EntranceConsts.KEY_ARCHIVE_CONFIG_URL, "")
        )
        if (mIsSearch) {
            val keyWord = searchBarBinding?.etSearch?.text?.toString()?.trim { it <= ' ' }
            bundle.putString(EntranceConsts.KEY_SEARCHKEY, keyWord)
            NewFlatLogUtils.logCloudArchiveSearchKeyUpload(
                mGameEntity?.id ?: "",
                mGameEntity?.name ?: "",
                keyWord ?: ""
            )
        }
        fragment.arguments = bundle
        childFragmentManager
            .beginTransaction()
            .replace(
                R.id.contentFragment,
                fragment,
                CloudArchiveListFragment::class.java.name
            )
            .commitAllowingStateLoss()
    }

    private fun changeSearchStatus(isSearch: Boolean) {
        when {
            mIsSearch != isSearch -> {
                mIsSearch = isSearch
                searchBarBinding?.tvBack?.goneIf(!mIsSearch)
                changeContentFragment()
            }

            mIsSearch -> {
                val keyWord = searchBarBinding?.etSearch?.text?.toString()?.trim { it <= ' ' } ?: ""
                NewFlatLogUtils.logCloudArchiveSearchKeyUpload(mGameEntity?.id ?: "", mGameEntity?.name ?: "", keyWord)
                mSearchFragment?.updateSearchKeyWord(keyWord)
            }
        }
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        if (mUseAlternativeLayout) {
            requireActivity().updateStatusBarColor(com.gh.gamecenter.common.R.color.ui_surface, com.gh.gamecenter.common.R.color.ui_surface)
        }
        mAlternativeBinding?.reuseToolbar?.run {
            normalToolbar.setBackgroundColor(
                com.gh.gamecenter.common.R.color.ui_surface.toColor(requireContext()))
            backBtn.setImageResource(com.gh.gamecenter.common.R.drawable.ic_bar_back)
            normalTitle.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(requireContext()))
        }
        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())
            )
        }
    }
}