package com.gh.gamecenter.personalhome.border

import android.graphics.Typeface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckedTextView
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.core.view.ViewCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.lifecycle.Observer
import com.gh.common.util.IntegralLogHelper
import com.gh.gamecenter.ImageViewerActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.fragment.ToolbarFragment
import com.gh.gamecenter.common.base.fragment.WaitingDialogFragment
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.databinding.FragmentAvatarBorderBinding
import com.gh.gamecenter.entity.AvatarBorderCategoryEntity
import com.gh.gamecenter.feature.entity.AvatarBorderEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.login.user.UserViewModel
import com.google.android.material.tabs.TabLayout
import com.halo.assistant.HaloApp
import com.halo.assistant.fragment.user.avatar.ChangeAvatarDialog
import org.json.JSONObject

class AvatarBorderFragment : ToolbarFragment() {

    private var mUserViewModel: UserViewModel? = null
    private var mAvatarBorderViewModel: AvatarBorderViewModel? = null
    private var mAvatarBorderCategories: List<AvatarBorderCategoryEntity>? = null
    private var mBinding: FragmentAvatarBorderBinding? = null

    private var mPostDialog: WaitingDialogFragment? = null
    var selectAvatarBorderEntity: AvatarBorderEntity? = null
    private val mTitleList = ArrayList<String>()
    private val mFragments = ArrayList<Fragment>()
    private var mCurrentIndex = 0
    private var mInitCategoryId = ""
    private var mInitTabIndex = 0
    private var mIsFirstIn = true

    override fun getLayoutId() = 0

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mInitCategoryId = arguments?.getString(EntranceConsts.KEY_CATEGORY_ID) ?: ""
        mAvatarBorderViewModel = viewModelProvider()
        mUserViewModel = viewModelProvider(UserViewModel.Factory(HaloApp.getInstance().application))
        mUserViewModel?.loginObsUserinfo?.observeNonNull(this) {
            mBinding?.run {
                if (it.data?.background?.url.isNullOrEmpty()) {
                    ImageUtils.display(forumBackground, R.drawable.bg_avatar_border)
                } else {
                    ImageUtils.display(forumBackground, it.data?.background?.url)
                }

                if (mIsFirstIn) {
                    userAvatar.display(it.data?.iconBorder?.url, it.data?.icon ?: "")
                    mIsFirstIn = false
                }
            }
        }

        mUserViewModel?.editObsUserinfo?.observe(this, Observer {
            mBinding?.run {
                userAvatar.displayAvatar(it.data?.icon ?: "")
            }
        })

        mUserViewModel?.uploadAvatarBorder?.observe(this, Observer {
            mPostDialog?.dismiss()
            if (it) {
                requireActivity().finish()
                mUserViewModel?.uploadAvatarBorder?.value = false
            }
        })

        mAvatarBorderViewModel?.pendantCategories?.observeNonNull(this) {
            if (it.isEmpty()) return@observeNonNull
            mAvatarBorderCategories = it
            initViewPager()
        }

        SPUtils.setString(Constants.SP_CHOOSE_AVATAR_ID, UserManager.getInstance().userInfoEntity?.iconBorder?.id ?: "")
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mBinding?.run {
            ViewCompat.setOnApplyWindowInsetsListener(appbar) { _, insets ->
                (toolbar.layoutParams as ViewGroup.MarginLayoutParams).topMargin = insets.systemWindowInsetTop
                insets.consumeSystemWindowInsets()
            }

            toolbar.setNavigationOnClickListener { requireActivity().finish() }

            collapsingToolbar.scrimShownAction = {
                DisplayUtils.setLightStatusBar(requireActivity(), it)
                if (it) {
                    titleTv.alpha = 1F
                    titleTv.setTextColor(ContextCompat.getColor(requireContext(), R.color.black))
                    toolbar.setNavigationIcon(R.drawable.ic_bar_back)
                    toolbar.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.white))
                    DisplayUtils.setStatusBarColor(requireActivity(), R.color.white, true)
                } else {
                    titleTv.setTextColor(ContextCompat.getColor(requireContext(), R.color.white))
                    toolbar.navigationIcon =
                        ContextCompat.getDrawable(requireContext(), R.drawable.ic_toolbar_back_white)
                    toolbar.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.transparent))
                    DisplayUtils.setStatusBarColor(requireActivity(), R.color.transparent, false)
                }
            }

            userAvatar.setOnClickListener {
                startActivity(
                    ImageViewerActivity.getIntent(
                        requireContext(), arrayListOf(
                            UserManager.getInstance().userInfoEntity?.icon
                                ?: ""
                        ), 0, arrayListOf(userAvatar.avatarView as View), "$mEntrance+(头像挂件)", true
                    )
                )
            }

            changeAvatarTv.setOnClickListener {
                IntegralLogHelper.log("click_change_profile_photo", "头像挂件页")
                ChangeAvatarDialog.show(requireActivity() as AppCompatActivity, tag ?: "")
            }

            commitTv.setOnClickListener {
                if (selectAvatarBorderEntity != null) {
                    mPostDialog = WaitingDialogFragment.newInstance("加载中...")
                    mPostDialog?.show(childFragmentManager, null)

                    val jsonObject = JSONObject()
                    if (commitTv.text == "停用挂件") {
                        IntegralLogHelper.logPendent(
                            "click_stop",
                            LOCATION,
                            selectAvatarBorderEntity!!.id,
                            mAvatarBorderCategories?.get(mCurrentIndex)?.id ?: ""
                        )

                        jsonObject.put("_id", "")
                        jsonObject.put("url", "")
                        mUserViewModel?.changeUserInfo(jsonObject.toString(), UserViewModel.TYPE_ICON_BORDER)
                    } else {
                        IntegralLogHelper.logPendent(
                            "click_use",
                            LOCATION,
                            selectAvatarBorderEntity!!.id,
                            mAvatarBorderCategories?.get(mCurrentIndex)?.id ?: ""
                        )

                        jsonObject.put("_id", selectAvatarBorderEntity?.id)
                        jsonObject.put("url", selectAvatarBorderEntity?.url)
                        mUserViewModel?.changeUserInfo(jsonObject.toString(), UserViewModel.TYPE_ICON_BORDER)
                    }
                }
            }
        }
    }

    fun choosePendant(entity: AvatarBorderEntity, isSelected: Boolean) {
        mBinding?.run {
            if (isSelected) {
                selectAvatarBorderEntity = entity
                userAvatar.displayBorder(entity.url)
                commitTv.isEnabled = true
                if (entity.id == UserManager.getInstance().userInfoEntity?.iconBorder?.id) {
                    commitTv.text = "停用挂件"
                } else {
                    commitTv.text = "使用"
                }
                commitTv.setTextColor(ContextCompat.getColor(requireContext(), R.color.white))
                commitTv.background =
                    ContextCompat.getDrawable(requireContext(), R.drawable.bg_notification_open_btn_style_2)
            } else {
                selectAvatarBorderEntity = null
                userAvatar.displayBorder(UserManager.getInstance().userInfoEntity?.iconBorder?.url)
                commitTv.text = "使用"
                commitTv.isEnabled = false
                commitTv.setTextColor(ContextCompat.getColor(requireContext(), R.color.text_body))
                commitTv.background = ContextCompat.getDrawable(requireContext(), R.drawable.border_round_eee_999)
            }
        }
    }

    private fun initViewPager() {
        mBinding?.run {
            mTitleList.clear()
            mFragments.clear()
            val tag = "android:switcher:${viewpager.id}:"
            mAvatarBorderCategories?.forEachIndexed { index, entity ->
                if (mInitCategoryId.isNotBlank() && mInitCategoryId == entity.id) {
                    mInitTabIndex = index
                }
                mTitleList.add(entity.name)
                val chooseAvatarBorderFragment = childFragmentManager.findFragmentByTag("$tag$index")
                    ?: ChooseAvatarBorderFragment().with(
                        bundleOf(
                            EntranceConsts.KEY_CATEGORY_ID to entity.id,
                            EntranceConsts.KEY_IS_FREE to entity.isFree
                        )
                    )
                mFragments.add(chooseAvatarBorderFragment)
            }

            viewpager.offscreenPageLimit = mFragments.size
            viewpager.adapter =
                object : FragmentStatePagerAdapter(childFragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
                    override fun getItem(position: Int) = mFragments[position]

                    override fun getCount() = mFragments.size

                    override fun getPageTitle(position: Int): CharSequence? {
                        return if (mTitleList.size > position) {
                            mTitleList[position]
                        } else super.getPageTitle(position)
                    }
                }
            tabLayout.setupWithViewPager(viewpager)

            for (i in 0 until tabLayout.tabCount) {
                val tab = tabLayout.getTabAt(i) ?: continue
                val tabTitle = if (tab.text != null) tab.text.toString() else ""
                val tabView = getTabView(tabTitle)
                tab.customView = tabView
                val padRight = if (i == tabLayout.tabCount - 1) 16F.dip2px() else 8F.dip2px()
                tab.view.setPadding(16F.dip2px(), 0, padRight, 0)
            }

            viewpager.currentItem = mInitTabIndex
            tabLayout.getTabAt(mInitTabIndex)?.let { updateTabStyle(it, true) }

            tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
                override fun onTabReselected(tab: TabLayout.Tab?) {
                    updateTabStyle(tab, true)
                }

                override fun onTabUnselected(tab: TabLayout.Tab?) {
                    updateTabStyle(tab, false)
                }

                override fun onTabSelected(tab: TabLayout.Tab?) {
                    updateTabStyle(tab, true)
                    tab?.run {
                        mAvatarBorderCategories?.get(position)?.run {
                            IntegralLogHelper.logPendent(
                                "click_tab_pendant_catalog",
                                LOCATION,
                                id
                            )
                        }
                    }
                }
            })

            viewpager.doOnPageSelected {
                mCurrentIndex = it
            }
        }
    }

    private fun getTabView(title: String): View {
        val view = LayoutInflater.from(requireContext()).inflate(R.layout.tab_item_avatar_border, null)
        val tabTitle = view.findViewById<View>(R.id.tab_title)
        if (tabTitle is CheckedTextView) {
            tabTitle.text = title
        }
        return view
    }

    private fun updateTabStyle(tab: TabLayout.Tab?, isChecked: Boolean) {
        val tabView = tab?.customView
        tabView?.run {
            val tabIndicator = findViewById<ImageView>(R.id.tab_indicator)
            val tabTitle = findViewById<TextView>(R.id.tab_title)
            tabIndicator.visibility = if (isChecked) View.VISIBLE else View.INVISIBLE
            tabTitle.typeface = if (isChecked) Typeface.DEFAULT_BOLD else Typeface.DEFAULT
        }
    }

    fun setBottomVisible(visible: Boolean) {
        mBinding?.bottomContainer?.visibility = if (visible) View.VISIBLE else View.GONE
    }

    companion object {
        const val LOCATION = "头像挂件页"
    }
}