package com.gh.gamecenter.qa.dialog

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Build
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import androidx.core.widget.doOnTextChanged
import androidx.fragment.app.Fragment
import com.gh.gamecenter.common.base.activity.BaseActivity
import com.gh.gamecenter.common.base.adapter.FragmentAdapter
import com.gh.common.util.*
import com.gh.gamecenter.R
import com.gh.gamecenter.SearchType
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.doOnPageSelected
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.core.utils.doOnEnd
import com.gh.gamecenter.databinding.DialogChooseForumBinding
import com.gh.gamecenter.common.entity.CommunityEntity

/**
 * 选择论坛
 */
class ChooseForumActivity : BaseActivity() {
    private lateinit var binding: DialogChooseForumBinding
    private var mSearchResultFragment: ChooseForumContainerFragment? = null
    private val mTabTitleList = arrayListOf("我的关注", "热门论坛")
    private val mFragmentsList: ArrayList<Fragment> = arrayListOf()

    override fun getLayoutId(): Int = R.layout.dialog_choose_forum

    @SuppressLint("ClickableViewAccessibility")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (Build.VERSION.SDK_INT != Build.VERSION_CODES.O) {
            requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        }
        DisplayUtils.transparentStatusBar(this)
        binding = DialogChooseForumBinding.bind(mContentView)

        val sourceEntrance = intent.getStringExtra(EntranceConsts.KEY_SOURCE_ENTRANCE) ?: ""

        initViewPager()
        binding.searchEt.doOnTextChanged { _, _, _, _ ->
            val searchKey = binding.searchEt.text?.toString()
            if (searchKey.isNullOrEmpty()) {
                switchUI(false)
            } else {
                switchUI(true)
                mSearchResultFragment?.setSearchKeyAndType(searchKey, SearchType.MANUAL.value)
            }
        }
        binding.searchEt.setOnTouchListener { _, event ->
            if (event.action == MotionEvent.ACTION_UP) {
                NewLogUtils.logForumSearchEnter("选择论坛面板搜索栏")
                NewLogUtils.logChooseForumPanelClick("view_select_forum_panel_search_box", "选择论坛面板搜索栏", "", "")
            }
            false
        }
        binding.closeIv.setOnClickListener {
            NewLogUtils.logChooseForumPanelClick("click_select_forum_panel_close", "", "", "")
            finish()
        }
        binding.maskView.alpha = 0f
        binding.maskView.animate().alpha(1f).setDuration(300).start()
        binding.maskView.setOnClickListener { binding.closeIv.performClick() }
        binding.forumContainer.translationY = (DisplayUtils.getScreenHeight()).toFloat()
        binding.forumContainer.animate().translationY(0f).setDuration(300).start()
    }

    private fun initViewPager() {
        mFragmentsList.clear()
        mFragmentsList.add(ChooseForumContainerFragment.getInstance(ChooseForumContainerFragment.ChooseForumType.ATTENTION))
        mFragmentsList.add(ChooseForumContainerFragment.getInstance(ChooseForumContainerFragment.ChooseForumType.HOT))
        binding.viewPager.offscreenPageLimit = mFragmentsList.size
        binding.viewPager.adapter =
            FragmentAdapter(supportFragmentManager, mFragmentsList, mTabTitleList)
        binding.tabLayout.setupWithViewPager(binding.viewPager)
        binding.tabIndicator.setupWithTabLayout(binding.tabLayout)
        binding.tabIndicator.setupWithViewPager(binding.viewPager)
        binding.tabIndicator.setIndicatorWidth(20)
        binding.viewPager.doOnPageSelected {
            NewLogUtils.logChooseForumPanelClick(if (it == 0) "click_my_follow_tab" else "click_hot_tab", "", "", "")
        }
    }

    private fun switchUI(isSearch: Boolean) {
        if (isSearch) {
            binding.tabContainer.visibility = View.GONE
            binding.line.visibility = View.GONE
            binding.viewPager.visibility = View.GONE
            binding.searchResultContainer.visibility = View.VISIBLE

            if (mSearchResultFragment == null || mSearchResultFragment?.isAdded == false) {
                val beginTransaction = supportFragmentManager.beginTransaction()
                mSearchResultFragment =
                    supportFragmentManager.findFragmentByTag(ChooseForumContainerFragment::class.java.name) as? ChooseForumContainerFragment
                        ?: ChooseForumContainerFragment.getInstance(ChooseForumContainerFragment.ChooseForumType.SEARCH) as ChooseForumContainerFragment
                beginTransaction.replace(
                    binding.searchResultContainer.id,
                    mSearchResultFragment!!,
                    ChooseForumContainerFragment::class.java.name
                )
                beginTransaction.commitAllowingStateLoss()
            }
        } else {
            binding.tabContainer.visibility = View.VISIBLE
            binding.line.visibility = View.VISIBLE
            binding.viewPager.visibility = View.VISIBLE
            binding.searchResultContainer.visibility = View.GONE
        }
    }

    fun chooseSuccess(community: CommunityEntity) {
        val intent = Intent()
        intent.putExtra(EntranceConsts.KEY_COMMUNITY_DATA, community)
        setResult(Activity.RESULT_OK, intent)
        finish()
    }

    fun switchTab(position: Int) {
        binding.viewPager.currentItem = position
    }

    override fun finish() {
        overridePendingTransition(0, 0)
        binding.maskView.animate().alpha(0f).setDuration(300).start()
        binding.forumContainer.animate()
            .translationY(DisplayUtils.getScreenHeight().toFloat())
            .setDuration(300)
            .doOnEnd {
                super.finish()
            }
            .start()
    }

    override fun isAutoResetViewBackgroundEnabled(): Boolean = true

    companion object {
        const val CHOOSE_FORUM_REQUEST = 10

        fun startChooseForumActivity(context: Activity, sourceEntrance: String) {
            val intent = Intent(context, ChooseForumActivity::class.java)
            intent.putExtra(EntranceConsts.KEY_SOURCE_ENTRANCE, sourceEntrance)
            context.overridePendingTransition(0, 0)
            context.startActivityForResult(intent, CHOOSE_FORUM_REQUEST)
        }
    }
}