package com.gh.gamecenter.gamecollection.tag

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.common.utils.viewModelProvider
import com.gh.gamecenter.R
import com.gh.gamecenter.databinding.FragmentGameCollectionTagSelectBinding
import com.gh.gamecenter.databinding.ItemGameCollectionSelectedTagBinding
import com.gh.gamecenter.entity.TagInfoEntity
import com.gh.gamecenter.common.base.fragment.ToolbarFragment
import com.gh.gamecenter.common.utils.toColor

class GameCollectionTagSelectFragment : ToolbarFragment() {

    private var mSingleChoice = false
    private var mMaxSelectCount = 1
    private var mSelectedTag: TagInfoEntity? = null
    private var mSelectedTags: ArrayList<TagInfoEntity>? = null
    private lateinit var mBinding: FragmentGameCollectionTagSelectBinding
    private lateinit var mAdapter: GameCollectionTagAdapter
    private lateinit var mViewModel: GameCollectionTagViewModel
    private var firstVisibleItemPosition = 0

    private val updateSelectedTagView: (() -> Unit) = {
        mAdapter.selectedTagEntityList.let { list ->
            mBinding.selectedTagContainer.removeAllViews()
            for (tag in list) {
                val selectedTagView = ItemGameCollectionSelectedTagBinding.inflate(layoutInflater)
                selectedTagView.run {
                    tagTv.text = tag.name
                    root.setOnClickListener {
                        list.remove(tag)
                        mBinding.selectedTagContainer.removeView(selectedTagView.root)
                        mAdapter.notifyDataSetChanged()
                        mBinding.selectedTagScrollView.visibility =
                            if (firstVisibleItemPosition == 0 || list.isEmpty()) View.GONE else View.VISIBLE
                    }
                }
                mBinding.selectedTagContainer.addView(selectedTagView.root)
            }
            mBinding.selectedTagScrollView.visibility =
                if (firstVisibleItemPosition == 0 || list.isEmpty()) View.GONE else View.VISIBLE
        }
    }

    override fun getLayoutId(): Int = 0

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

    override fun onMenuItemClick(menuItem: MenuItem?) {
        if (menuItem?.itemId == R.id.layout_menu_save) {
            if (!mSingleChoice) {
                requireActivity().setResult(
                    Activity.RESULT_OK,
                    Intent().putExtra(SELECTED_TAG, mAdapter.selectedTagEntityList)
                )
            }
            requireActivity().finish()
        } else {
            mAdapter.selectedTagEntity = null
            mAdapter.selectedTagCategory = ""
            mAdapter.notifyDataSetChanged()
            back()
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mSingleChoice = arguments?.getBoolean(GameCollectionTagSelectActivity.KEY_IS_SINGLE_CHOICE) ?: false
        mSelectedTag = arguments?.getParcelable(GameCollectionTagSelectActivity.KEY_SINGLE_SELECTED_TAG)
        mMaxSelectCount = arguments?.getInt(GameCollectionTagSelectActivity.KEY_MAX_SELECT_COUNT_TAG, 1) ?: 1
        mSelectedTags =
            arguments?.getParcelableArrayList(GameCollectionTagSelectActivity.KEY_SELECT_TAGS) ?: arrayListOf()
        mAdapter = GameCollectionTagAdapter(
            requireContext(),
            mSingleChoice,
            mMaxSelectCount,
            mSelectedTag,
            updateSelectedTagView,
            { back() })
        if (!mSelectedTags.isNullOrEmpty()) {
            mAdapter.selectedTagEntityList.addAll(mSelectedTags!!)
        }
        mViewModel = viewModelProvider()
        if (mSingleChoice) NewLogUtils.logEnterGameCollectionTag()
        mBinding.tagRv.run {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = mAdapter
            addOnScrollListener(object : RecyclerView.OnScrollListener() {

                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)
                    firstVisibleItemPosition = (layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()
                    mBinding.selectedTagScrollView.visibility =
                        if (firstVisibleItemPosition == 0 || mAdapter.selectedTagEntityList.isEmpty()) View.GONE else View.VISIBLE
                }
            })
            (itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
        }

        mViewModel.tagListLiveData.observe(viewLifecycleOwner) {
            mAdapter.setTagList(it)
        }
    }

    private fun back() {
        if (mAdapter.selectedTagEntity != null) {
            NewLogUtils.logFilterGameCollectionTag(mAdapter.selectedTagCategory, mAdapter.selectedTagEntity!!.name)
        }
        requireActivity().setResult(
            Activity.RESULT_OK,
            Intent().putExtra(SELECTED_TAG, mAdapter.selectedTagEntity)
        )
        requireActivity().finish()
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        mBinding.root.setBackgroundColor(R.color.background_white.toColor(requireContext()))
        mBinding.selectedTagScrollView.setBackgroundColor(R.color.background_white.toColor(requireContext()))
        if (::mAdapter.isInitialized) {
            mAdapter.notifyItemRangeChanged(0, mAdapter.itemCount)
        }
    }

    companion object {
        const val SELECTED_TAG = "selected_tag"
    }
}