package com.gh.gamecenter.feedback.view.qa

import android.app.Dialog
import android.content.res.Configuration
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.Lifecycle
import androidx.recyclerview.widget.GridLayoutManager
import com.therouter.TheRouter
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.eventbus.EBReuse
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.utils.DarkModeUtils.isDarkModeOn
import com.gh.gamecenter.common.utils.DarkModeUtils.isFollowSystemDarkModeFromSp
import com.gh.gamecenter.common.view.GridSpacingItemDecoration
import com.gh.gamecenter.core.provider.IAppProvider
import com.gh.gamecenter.core.provider.IDialogUtilsProvider
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.feedback.R
import com.gh.gamecenter.feedback.databinding.DialogQaFeedbackBinding
import com.gh.gamecenter.feedback.view.suggest.SuggestionActivity
import com.lightgame.dialog.BaseDialogFragment
import org.greenrobot.eventbus.EventBus

class QaFeedbackDialogFragment : BaseDialogFragment() {
    var contentId: String = ""
    private var mLoadingDialog: Dialog? = null
    private lateinit var mBinding: DialogQaFeedbackBinding
    private lateinit var mViewModel: QaFeedbackViewModel
    private val mReasonList = arrayListOf("内容看不懂", "没有解决办法", "方法不可行", "其他原因")
    private lateinit var mAdapter: QaFeedbackReasonAdapter

    private var mIsDarkModeOn = false

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mViewModel = viewModelProvider(QaFeedbackViewModel.Factory(contentId))
        mViewModel.feedbackSuccess.observe(this) {
            if (it) {
                ToastUtils.showToast("感谢您的反馈")
                EventBus.getDefault().post(EBReuse("feedbackRefresh"))
                dismissAllowingStateLoss()
            }
            mLoadingDialog?.dismiss()
        }

        mIsDarkModeOn = isDarkModeOn(requireContext())
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mBinding.contentEt.filters = arrayOf(TextHelper.getFilter(300, "最多允许输入300个字"))
        mBinding.reasonRv.apply {
            layoutManager = GridLayoutManager(requireContext(), 2)
            addItemDecoration(GridSpacingItemDecoration(2, 8f.dip2px(), false))
            adapter = QaFeedbackReasonAdapter(requireContext(), mReasonList) {
                mBinding.commitBtn.background =
                    com.gh.gamecenter.common.R.drawable.bg_notification_open_btn_style_2.toDrawable(requireContext())
                mBinding.commitBtn.setTextColor(com.gh.gamecenter.common.R.color.text_white.toColor(requireContext()))
            }.apply {
                mAdapter = this
            }
        }
        mBinding.commitBtn.setOnClickListener {
            val reason = mAdapter.getSelectReason()
            if (reason.isEmpty()) return@setOnClickListener
            qaFeedback(reason)
        }
        mBinding.feedbackMoreTv.setOnClickListener {
            requireContext().startActivity(SuggestionActivity.getSuggestGameIntent(requireContext()))
        }
        mBinding.closeIv.setOnClickListener {
            dismissAllowingStateLoss()
        }
    }

    private fun qaFeedback(reason: String) {
        if (contentId.isEmpty()) return
        val appProvider = TheRouter.get(IAppProvider::class.java)
        val gameName = appProvider?.get(Constants.GAME_NAME, false) as? String
        val headStr = if (gameName.isNullOrEmpty()) {
            "【没帮助】"
        } else {
            //https://git.shanqu.cc/pm/halo/halo-app-issues/-/issues/1928 第4点
            "【来自：${gameName}-没帮助】"
        }
        val sb = StringBuilder(headStr).append(contentId).append("；").append(reason)
        if (mBinding.contentEt.text.isNotEmpty()) {
            sb.append("；")
            sb.append(mBinding.contentEt.text.toString().trim())
        }
        val dialogUtils = TheRouter.get(IDialogUtilsProvider::class.java)
        mLoadingDialog = dialogUtils?.showWaitDialog(requireContext(), "提交中...")
        mViewModel.qaSuggestions(sb.toString())
    }


    override fun onStart() {
        super.onStart()
        val width = requireContext().resources.displayMetrics.widthPixels - 40F.dip2px()
        val height = ViewGroup.LayoutParams.WRAP_CONTENT
        requireDialog().window?.setLayout(width, height)
        requireDialog().setCanceledOnTouchOutside(false)
    }

    override fun onResume() {
        super.onResume()
        if (!isFollowSystemDarkModeFromSp() && mIsDarkModeOn != isDarkModeOn(requireContext())) {
            onDarkModeChanged()
        }
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        onDarkModeChanged()
    }

    private fun onDarkModeChanged() {
        mIsDarkModeOn = isDarkModeOn(requireContext())

        mBinding.run {
            root.background = com.gh.gamecenter.common.R.drawable.background_shape_white_radius_8.toDrawable(requireContext())
            title.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(requireContext()))
            reasonRv.adapter?.run {
                notifyItemRangeChanged(0, itemCount)
            }
            contentEt.run {
                background = R.drawable.border_round_stroke_eee_4.toDrawable(requireContext())
                setHintTextColor(com.gh.gamecenter.common.R.color.text_instance.toColor(requireContext()))
                setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(requireContext()))
            }
            commitBtn.run {
                if (::mAdapter.isInitialized && mAdapter.getSelectReason().isEmpty()) {
                    background = com.gh.gamecenter.common.R.drawable.button_round_f5f5f5.toDrawable(requireContext())
                    setTextColor(com.gh.gamecenter.common.R.color.text_instance.toColor(requireContext()))
                } else {
                    background = com.gh.gamecenter.common.R.drawable.bg_notification_open_btn_style_2.toDrawable(requireContext())
                    setTextColor(com.gh.gamecenter.common.R.color.text_white.toColor(requireContext()))
                }
            }
            feedbackMoreTv.setTextColor(com.gh.gamecenter.common.R.color.text_theme.toColor(requireContext()))
        }
    }

    companion object {
        @JvmStatic
        fun show(activity: AppCompatActivity, contentId: String) {
            if (!activity.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) return
            var dialogFragment =
                activity.supportFragmentManager.findFragmentByTag(QaFeedbackDialogFragment::class.java.name) as? QaFeedbackDialogFragment
            if (dialogFragment == null) {
                dialogFragment = QaFeedbackDialogFragment()
                dialogFragment.contentId = contentId
                dialogFragment.show(
                    activity.supportFragmentManager,
                    QaFeedbackDialogFragment::class.java.name
                )
            } else {
                dialogFragment.contentId = contentId
                val transaction: FragmentTransaction =
                    activity.supportFragmentManager.beginTransaction()
                transaction.show(dialogFragment)
                transaction.commit()
            }
        }
    }
}