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

import android.annotation.SuppressLint
import android.text.Editable
import android.text.TextWatcher
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.activityViewModels
import com.adealink.frame.base.Rlt
import com.adealink.frame.locale.country.CountryCode
import com.adealink.frame.log.Log
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.util.onClick
import com.adealink.weparty.account.R
import com.adealink.weparty.account.constant.TAG_PHONE_LOGIN
import com.adealink.weparty.account.databinding.FragmentAccountInputPhoneBinding
import com.adealink.weparty.account.login.comp.OtherLoginWay
import com.adealink.weparty.account.login.phone.data.Page
import com.adealink.weparty.account.login.phone.viewmodel.PhoneLoginViewModel
import com.adealink.weparty.account.viewModel.AccountViewModelFactory
import com.adealink.weparty.commonui.BaseFragment
import com.adealink.weparty.commonui.ext.dp
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.commonui.toast.util.showFailedToast
import com.adealink.weparty.commonui.toast.util.showToast
import com.adealink.weparty.country.CountrySelectDialog
import com.adealink.weparty.country.data.CountryData
import com.adealink.weparty.country.viewmodel.CountryViewModel
import com.adealink.weparty.util.applyImmersive
import com.adealink.weparty.R as APP_R

class InputPhoneFragment : BaseFragment(R.layout.fragment_account_input_phone) {

    private val binding by viewBinding(FragmentAccountInputPhoneBinding::bind)

    private val phoneViewModel by activityViewModels<PhoneLoginViewModel> { AccountViewModelFactory() }
    private val countryViewModel by activityViewModels<CountryViewModel>()

    private var selectCountry: CountryData? = null
    override fun initViews() {
        super.initViews()
        activity.applyImmersive { top ->
            binding.topBar.updateLayoutParams<ConstraintLayout.LayoutParams> {
                topMargin = top
            }
        }
        binding.vOtherLogin.root.updateLayoutParams<ConstraintLayout.LayoutParams> {
            bottomMargin = 18.dp()
        }

        binding.ivCountry.onClick {
            selectCountry()
        }
        binding.tvCountryCode.onClick {
            selectCountry()
        }

        binding.etNumberInput.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(
                s: CharSequence?,
                start: Int,
                count: Int,
                after: Int
            ) {
            }

            override fun onTextChanged(
                s: CharSequence?,
                start: Int,
                before: Int,
                count: Int
            ) {
            }

            @SuppressLint("SetTextI18n")
            override fun afterTextChanged(s: Editable?) {
                updateSendButton()
                binding.ivClearInput.show(!s.isNullOrEmpty())
            }
        })

        binding.tvCountryCode.text = phoneViewModel.verifyPhoneRegion
        binding.etNumberInput.setText(phoneViewModel.verifyPhoneNumber)

        binding.btnVerify.isEnabled = false
        binding.ivClearInput.onClick {
            binding.etNumberInput.text = null
        }

        binding.btnVerify.onClick {
            sendVerifyCode()
        }
    }

    override fun initComponents() {
        super.initComponents()
        OtherLoginWay(this, binding.vOtherLogin).attach()
    }

    override fun loadData() {
        super.loadData()
        countryViewModel.loadCountryList().observe(viewLifecycleOwner) { list ->
            //选择默认国家
            //ID -> EN
            val id = list.find { it.code == CountryCode.ID.code }
            if (id != null) {
                onCountrySelect(id)
            } else {
                onCountrySelect(list.firstOrNull())
            }
        }
    }


    private fun selectCountry() {
        CountrySelectDialog().apply {
            setOnItemSelect {
                onCountrySelect(it.data)
            }
        }.show(childFragmentManager, "CountrySelectDialog")
    }

    private fun onCountrySelect(country: CountryData?) {
        this@InputPhoneFragment.selectCountry = country
        binding.ivCountry.setImageUrl(country?.icon)
        binding.tvCountryCode.text = country?.regionCode
        updateSendButton()
    }

    private fun updateSendButton() {
        binding.btnVerify.isEnabled = selectCountry != null
                && !binding.etNumberInput.text.isNullOrEmpty()
    }

    private fun sendVerifyCode() {
        val checkRlt = phoneViewModel.checkCanSendVerifyCode()
        if (checkRlt is Rlt.Failed) {
            showFailedToast(checkRlt)
            return
        }
        if (selectCountry == null) {
            showToast(APP_R.string.account_input_phone_country_code_empty)
            return
        }
        val regionCode = selectCountry?.regionCode
        if (regionCode.isNullOrEmpty()) {
            Log.e(
                TAG_PHONE_LOGIN,
                "sendVerifyCode fail, for selectCountry${selectCountry} code is null"
            )
            return
        }
        val number = binding.etNumberInput.text?.toString()
        if (number.isNullOrEmpty()) {
            showToast(APP_R.string.account_input_phone_number_empty)
            return
        }
        showLoading()
        phoneViewModel.sendVerifyCode(regionCode, number)
            .observe(viewLifecycleOwner) { sendVerifyRlt ->
                dismissLoading()
                when (sendVerifyRlt.rlt) {
                    is Rlt.Failed -> {
                        showFailedToast(sendVerifyRlt.rlt)
                    }

                    is Rlt.Success -> {
                        phoneViewModel.showPage(Page.VERIFY)
                    }
                }
            }
    }

}