package com.gh.gamecenter.gamecollection.publish

import android.app.Activity
import android.app.Dialog
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.os.bundleOf
import androidx.recyclerview.widget.GridLayoutManager
import com.gh.gamecenter.common.base.fragment.BaseDialogFragment
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.common.view.GridSpacingItemColorDecoration
import com.gh.gamecenter.R
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.databinding.DialogChooseGameCollectionDefaultCoverBinding
import com.halo.assistant.HaloApp
import kotlin.math.ceil

class ChooseGameCollectionDefaultCoverDialog : BaseDialogFragment() {

    private lateinit var mBinding: DialogChooseGameCollectionDefaultCoverBinding
    private var mViewModel: ChooseGameCollectionDefaultCoverViewModel? = null
    private var mAdapter: ChooseGameCollectionDefaultAdapter? = null
    private var mItemDecoration: RecyclerView.ItemDecoration? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return DialogChooseGameCollectionDefaultCoverBinding.inflate(layoutInflater, null, false).apply {
            mBinding = this
        }.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val itemWidth = (DisplayUtils.getScreenWidth() - 16f.dip2px() * 2 - 8f.dip2px()) / 2
        val itemHeight = itemWidth * 69 / 160f
        val coverRvHeight = itemHeight * 3 + 8f.dip2px() * 2
        mBinding.coverRv.apply {
            val params = layoutParams as ConstraintLayout.LayoutParams
            params.height = ceil(coverRvHeight).toInt()
            layoutParams = params
            if (mAdapter == null) {
                mAdapter = ChooseGameCollectionDefaultAdapter(requireContext()) {
                    val tag = requireArguments().getString(EntranceConsts.KEY_PARENT_TAG)
                    val intent = Intent().apply {
                        putExtra(EntranceConsts.KEY_DATA, it)
                    }
                    requireActivity().supportFragmentManager.findFragmentByTag(tag)
                        ?.onActivityResult(REQUEST_CODE_DEFAULT_IMAGE, Activity.RESULT_OK, intent)
                    dismissAllowingStateLoss()
                }
            }
            adapter = mAdapter
            layoutManager = GridLayoutManager(requireContext(), 2)
            addItemDecoration(
                GridSpacingItemColorDecoration(
                    context,
                    8,
                    R.color.background_white
                ).apply { mItemDecoration = this })
        }

        mViewModel = viewModelProvider()
        mViewModel?.coverListLivedata?.observe(viewLifecycleOwner) {
            mBinding.reuseLlLoading.root.visibility = View.GONE
            if (it != null) {
                mAdapter?.submitList(it)
            }
        }

        mBinding.changeBatchBtn.setOnClickListener {
            mViewModel?.getRandomCover()
            NewLogUtils.logClickGameCollectionDefaultCoverDialog("换一换")
        }
        mBinding.cancelBtn.setOnClickListener {
            dismissAllowingStateLoss()
        }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val createDialog = super.onCreateDialog(savedInstanceState)
        createDialog.setCanceledOnTouchOutside(true)
        val window = createDialog.window
        window?.setGravity(Gravity.BOTTOM)
        window?.setWindowAnimations(R.style.community_publication_animation)
        return createDialog
    }

    override fun onStart() {
        super.onStart()
        val width = HaloApp.getInstance().application.resources.displayMetrics.widthPixels
        val height = dialog?.window?.attributes?.height ?: ViewGroup.LayoutParams.WRAP_CONTENT
        dialog?.window?.setLayout(width, height)
    }

    override fun onDismiss(dialog: DialogInterface) {
        super.onDismiss(dialog)
        NewLogUtils.logClickGameCollectionDefaultCoverDialog("关闭弹窗")
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        mAdapter?.let { it.notifyItemRangeChanged(0, it.itemCount) }
        if (::mBinding.isInitialized) {
            mBinding.run {
                root.setRootBackgroundDrawable(R.drawable.background_shape_white_radius_12_top_only)
                cancelBtn.background = R.drawable.bg_shape_f5_radius_999.toDrawable(requireContext())
                titleTv.setTextColor(R.color.text_title.toColor(requireContext()))
                changeBatchBtn.setTextColor(R.color.theme_font.toColor(requireContext()))
                cancelBtn.setTextColor(R.color.text_subtitle.toColor(requireContext()))
                coverRv.run {
                    mItemDecoration?.let { removeItemDecoration(it) }
                    addItemDecoration(
                        GridSpacingItemColorDecoration(
                            context,
                            8,
                            R.color.background_white
                        ).apply { mItemDecoration = this })
                }
            }
        }
    }

    companion object {
        const val REQUEST_CODE_DEFAULT_IMAGE = 104

        fun show(activity: AppCompatActivity, parentTag: String) {
            ChooseGameCollectionDefaultCoverDialog().apply {
                arguments = bundleOf(
                    EntranceConsts.KEY_PARENT_TAG to parentTag
                )
            }.show(activity.supportFragmentManager, ChooseGameCollectionDefaultCoverDialog::class.java.name)
        }
    }
}