package com.halo.assistant.fragment.user.avatar

import android.app.Activity
import android.app.Dialog
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.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import com.gh.common.util.DialogUtils
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.activity.BaseActivity
import com.gh.gamecenter.common.base.fragment.BaseDialogFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.observeNonNull
import com.gh.gamecenter.common.utils.viewModelProvider
import com.gh.gamecenter.common.view.GridSpacingItemColorDecoration
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.databinding.DialogChooseDefaultAvatarBinding
import com.gh.gamecenter.login.user.UserViewModel
import com.halo.assistant.HaloApp
import kotlin.math.ceil

class ChooseDefaultAvatarDialog : BaseDialogFragment() {

    private lateinit var mBinding: DialogChooseDefaultAvatarBinding
    private var mViewModel: ChooseDefaultAvatarViewModel? = null
    private var mUserViewModel: UserViewModel? = null
    private var mAdapter: DefaultAvatarAdapter? = null
    private var mLoadingDialog: Dialog? = null
    private var mUploadAvatar = false

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mViewModel = viewModelProvider()
        mUserViewModel = viewModelProvider(UserViewModel.Factory(HaloApp.getInstance().application))

        mBinding.avatarRv.apply {
            if (mAdapter == null && mViewModel != null) {
                mAdapter = DefaultAvatarAdapter(requireContext(), mViewModel!!) {
                    NewFlatLogUtils.logDefaultAvatarDialogClick("头像")
                    mViewModel?.defaultAvatar = if (mViewModel?.defaultAvatar == it) null else it
                    mAdapter?.run {
                        notifyItemRangeChanged(0, itemCount)
                        mBinding.confirmBtn.alpha = if (mViewModel?.defaultAvatar == null) 0.4F else 1F
                    }
                }
            }
            (itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false
            adapter = mAdapter
            layoutManager = GridLayoutManager(requireContext(), 4)
            addItemDecoration(
                GridSpacingItemColorDecoration(
                    context,
                    3,
                    8,
                    R.color.transparent
                )
            )
        }
        mViewModel?.avatarListLivedata?.observeNonNull(viewLifecycleOwner) {
            mBinding.reuseLlLoading.root.visibility = View.GONE
            mAdapter?.submitList(it)
        }
        mUserViewModel?.editObsUserinfo?.observe(this) {
            if (mLoadingDialog != null) {
                mLoadingDialog!!.dismiss()
            }
            if (mLoadingDialog != null && it != null && it.data != null && mUploadAvatar) {
                val tag = requireArguments().getString(EntranceConsts.KEY_PARENT_TAG)
                val intent = Intent().apply {
                    putExtra(EntranceConsts.KEY_DATA, it.data.icon)
                }
                requireActivity().supportFragmentManager.findFragmentByTag(tag)
                    ?.onActivityResult(REQUEST_CODE_DEFAULT_AVATAR, Activity.RESULT_OK, intent)
                dismissAllowingStateLoss()
            }
        }
        mBinding.cancelBtn.setOnClickListener {
            NewFlatLogUtils.logDefaultAvatarDialogClick("关闭")
            dismissAllowingStateLoss()
        }
        mBinding.confirmBtn.setOnClickListener {
            NewFlatLogUtils.logDefaultAvatarDialogClick("确定")
            if (mViewModel?.defaultAvatar != null) {
                mLoadingDialog = DialogUtils.showWaitDialog(activity, "正在修改信息...")
                mUserViewModel?.changeUserInfo(mViewModel?.defaultAvatar?.url, UserViewModel.TYPE_PORTRAIT)
                mUploadAvatar = true
            } else {
                ToastUtils.toast("请选择默认头像")
            }
        }
    }

    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 onDarkModeChanged() {
        BaseActivity.updateStaticView(mBinding.root, emptyList())
        mAdapter?.let { it.notifyItemRangeChanged(0, it.itemCount) }
    }

    companion object {
        const val REQUEST_CODE_DEFAULT_AVATAR = 101

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