package com.gh.gamecenter.feature.view.dialog

import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.*
import androidx.appcompat.app.AppCompatActivity
import androidx.core.os.bundleOf
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.GridLayoutManager
import com.gh.gamecenter.common.HaloApp
import com.gh.gamecenter.common.R
import com.gh.gamecenter.common.base.fragment.BaseDialogFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.observeNonNull
import com.gh.gamecenter.common.utils.viewModelProviderFromParent
import com.gh.gamecenter.feature.databinding.DialogManualInputBinding
import com.gh.gamecenter.feature.databinding.DialogSelectGameBinding
import com.gh.gamecenter.feature.game.SuggestSelectGameAdapter
import com.lightgame.utils.Util_System_Keyboard

class SelectGameDialogFragment : BaseDialogFragment() {
    private var mAdapter: SuggestSelectGameAdapter? = null
    private lateinit var mBinding: DialogSelectGameBinding
    private lateinit var mViewModel: SelectGameViewModel

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val parentTag = requireArguments().getString(EntranceConsts.KEY_PARENT_TAG) ?: ""
        mViewModel = viewModelProviderFromParent()
        mAdapter = SuggestSelectGameAdapter(requireContext(), "") {
            val intent = Intent().apply {
                putExtra(EntranceConsts.KEY_GAME_NAME, it.gameName)
                putExtra(EntranceConsts.KEY_GAME_INFO, "${it.gameName}(${it.packageName}, ${it.gameVersion})")
            }
            requireActivity().supportFragmentManager.findFragmentByTag(parentTag)
                ?.onActivityResult(REQUEST_CODE_SELECT_GAME, Activity.RESULT_OK, intent)
            dismissAllowingStateLoss()
        }
        mBinding.gameRv.layoutManager = GridLayoutManager(requireContext(), 4)
        mBinding.gameRv.adapter = mAdapter
        mBinding.manualInputTv.setOnClickListener {
            showManualInputDialog(requireActivity(), parentTag)
            dismissAllowingStateLoss()
        }
        mBinding.closeIv.setOnClickListener {
            dismissAllowingStateLoss()
        }
        mViewModel.gameListLiveData.observeNonNull(this) {
            mAdapter?.submitList(it)
            mBinding.reuseLlLoading.root.visibility = View.GONE
        }
    }

    private fun showManualInputDialog(activity: FragmentActivity, parentTag: String) {
        val dialog = Dialog(activity)
        val binding = DialogManualInputBinding.inflate(LayoutInflater.from(activity))
        binding.confirmTv.setOnClickListener {
            val intent = Intent().apply {
                putExtra(EntranceConsts.KEY_GAME_NAME, binding.contentEt.text.toString())
                putExtra(EntranceConsts.KEY_GAME_INFO, binding.contentEt.text.toString())
            }
            activity.supportFragmentManager.findFragmentByTag(parentTag)
                ?.onActivityResult(REQUEST_CODE_SELECT_GAME, Activity.RESULT_OK, intent)
            dialog.dismiss()
        }
        binding.cancelTv.setOnClickListener {
            dialog.dismiss()
        }
        binding.contentEt.addTextChangedListener { s ->
            binding.confirmTv.isEnabled = !s.isNullOrEmpty()
            binding.confirmTv.alpha = if (s.isNullOrEmpty()) 0.4F else 1F
        }
        dialog.setOnDismissListener {
            Util_System_Keyboard.hideSoftKeyboard(activity)
        }
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialog.setContentView(binding.root)
        dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        dialog.show()
        binding.root.postDelayed({
            binding.contentEt.requestFocus()
            Util_System_Keyboard.showSoftKeyboard(
                activity,
                binding.contentEt
            )
        }, 300)
    }

    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().resources.displayMetrics.widthPixels
        val height = dialog?.window?.attributes?.height ?: ViewGroup.LayoutParams.WRAP_CONTENT
        dialog?.window?.setLayout(width, height)
    }

    companion object {
        const val REQUEST_CODE_SELECT_GAME = 200

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