package com.adealink.weparty.joinus.step1.page

import android.annotation.SuppressLint
import android.text.Editable
import android.text.TextWatcher
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updatePadding
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.commonui.BaseFragment
import com.adealink.weparty.commonui.ext.contentView
import com.adealink.weparty.commonui.ext.fitSystemWindows
import com.adealink.weparty.commonui.ext.onWindowInsets
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.joinus.R
import com.adealink.weparty.joinus.data.TAG_JOINUS_STEP1
import com.adealink.weparty.joinus.databinding.FragmentJoinUsStep1InputPhoneBinding
import com.adealink.weparty.joinus.step1.JoinUsStep1Fragment
import com.adealink.weparty.joinus.step1.data.Step1Page
import com.adealink.weparty.joinus.step1.viewmodel.Step1ViewModel
import com.adealink.weparty.viewmodel.parentFragmentViewModels
import com.adealink.weparty.R as APP_R

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


    private val binding by viewBinding(FragmentJoinUsStep1InputPhoneBinding::bind)

    private val step1ViewModel by parentFragmentViewModels<Step1ViewModel, JoinUsStep1Fragment>(
        JoinUsStep1Fragment::class.java
    )

    private val countryViewModel by activityViewModels<CountryViewModel>()

    private var selectCountry: CountryData? = null
    override fun initViews() {
        super.initViews()
        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.ivClearInput.onClick {
            binding.etNumberInput.text = null
        }

        binding.btnVerify.isEnabled = false

        binding.btnVerify.onClick {
            sendVerifyCode()
        }
        fitWindow()
    }

    private fun fitWindow() {
        // 关键：只在需要的时候设置
        activity?.window?.fitSystemWindows(false)
        // 内容布局处理键盘
        val contentView = activity?.contentView() ?: return
        contentView.onWindowInsets { view, insets ->
            val ime = insets.getInsets(WindowInsetsCompat.Type.ime())

            // 键盘显示时使用键盘高度，否则使用导航栏高度
            val bottomInset = if (ime.bottom > 0) ime.bottom else 0
            view.updatePadding(bottom = bottomInset)
            insets
        }
    }

    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 = step1ViewModel.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_JOINUS_STEP1,
                "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()
        step1ViewModel.sendVerifyCode(regionCode, number)
            .observe(viewLifecycleOwner) { sendVerifyRlt ->
                dismissLoading()
                when (sendVerifyRlt.rlt) {
                    is Rlt.Failed -> {
                        showFailedToast(sendVerifyRlt.rlt)
                    }

                    is Rlt.Success -> {
                        step1ViewModel.showPage(Step1Page.INPUT_VERIFY)
                    }
                }
            }
    }

}