package com.adealink.weparty.account.login.phone

import android.content.Intent
import android.view.KeyEvent
import androidx.activity.viewModels
import com.adealink.frame.base.Rlt
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.router.Router
import com.adealink.frame.router.annotation.RouterUri
import com.adealink.weparty.account.R
import com.adealink.weparty.account.databinding.ActivityPhoneLoginBinding
import com.adealink.weparty.account.login.BaseLoginActivity
import com.adealink.weparty.account.login.phone.data.Page
import com.adealink.weparty.account.login.phone.fragment.InputPhoneFragment
import com.adealink.weparty.account.login.phone.fragment.VerifyPhoneFragment
import com.adealink.weparty.account.login.phone.viewmodel.PhoneLoginViewModel
import com.adealink.weparty.account.login.viewmodel.LoginViewModel
import com.adealink.weparty.account.viewModel.AccountViewModelFactory
import com.adealink.weparty.commonui.BaseFragment
import com.adealink.weparty.commonui.toast.util.showToast
import com.adealink.weparty.module.account.Account


@RouterUri(path = [Account.Phone.LOGIN], desc = "手机号码登录页面")
class PhoneLoginActivity : BaseLoginActivity() {

    companion object {
        private const val TAG_INPUT = "tag_input"
        private const val TAG_VERIFY = "tag_verify"
    }

    private val binding by viewBinding(ActivityPhoneLoginBinding::inflate)
    private val loginViewModel by viewModels<LoginViewModel> { AccountViewModelFactory() }
    private val phoneViewModel by viewModels<PhoneLoginViewModel> { AccountViewModelFactory() }
    private var currentFragment: BaseFragment? = null

    override fun onBeforeCreate() {
        super.onBeforeCreate()
        Router.bind(this)
    }

    override fun onAfterSuperCreate(): Boolean {
        loginViewModel.onNewIntent(intent)
        return super.onAfterSuperCreate()
    }

    override fun initViews() {
        super.initViews()
        setContentView(binding.root)
    }

    override fun observeViewModel() {
        super.observeViewModel()
        phoneViewModel.pageLD.observeWithoutCache(this) { page ->
            when (page) {
                Page.INPUT_PHONE -> {
                    inflateInputFragment()
                }

                Page.VERIFY -> {
                    inflateVerifyFragment()
                }
            }
        }
        loginViewModel.loginLD.observe(this) { rlt ->
            dismissLoading()
            val authType = rlt.authType
            when (val result = rlt.result) {
                is Rlt.Success -> {
                    handleLoginSuccess(
                        result.data,
                        authType,
                    )
                }

                is Rlt.Failed -> {
                    showToast(result)
                }
            }
        }
    }

    override fun loadData() {
        super.loadData()
        phoneViewModel.showPage(Page.INPUT_PHONE)
    }

    private fun inflateInputFragment() {
        var fragment =
            supportFragmentManager.findFragmentByTag(TAG_INPUT) as? InputPhoneFragment
        if (fragment?.isAdded == true) {
            return
        }

        fragment = fragment ?: InputPhoneFragment()
        currentFragment = fragment
        supportFragmentManager.beginTransaction()
            .replace(R.id.fl_content, fragment, TAG_INPUT)
            .commitAllowingStateLoss()
    }

    private fun inflateVerifyFragment() {
        var fragment =
            supportFragmentManager.findFragmentByTag(TAG_VERIFY) as? VerifyPhoneFragment
        if (fragment?.isAdded == true) {
            return
        }

        fragment = fragment ?: VerifyPhoneFragment()
        currentFragment = fragment
        supportFragmentManager.beginTransaction()
            .replace(R.id.fl_content, fragment, TAG_VERIFY)
            .commitAllowingStateLoss()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        loginViewModel.handleOnActivityResult(requestCode, resultCode, data)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (currentFragment?.onKeyDown(keyCode, event) == true) {
            return true
        }
        return super.onKeyDown(keyCode, event)
    }
}