package com.adealink.weparty.joinus.step2.comp

import android.annotation.SuppressLint
import android.text.Editable
import android.text.TextWatcher
import androidx.lifecycle.LifecycleOwner
import com.adealink.frame.mvvm.viewmodel.viewModels
import com.adealink.weparty.commonui.BaseViewComponent
import com.adealink.weparty.commonui.text.setMaxLength
import com.adealink.weparty.constant.PROFILE_NICKNAME_MAX_LENGTH
import com.adealink.weparty.joinus.databinding.LayoutJoinUsStep2EditNicknameBinding
import com.adealink.weparty.joinus.step2.viewmodel.Step2ViewModel
import com.adealink.weparty.joinus.viewmodel.JoinUsViewModelFactory
import com.adealink.weparty.util.QMUIKeyboardHelper

class EditNicknameComp(
    lifecycleOwner: LifecycleOwner,
    private val binding: LayoutJoinUsStep2EditNicknameBinding
) : BaseViewComponent(lifecycleOwner) {

    companion object {
        private const val TAG = "EditNicknameComp"
    }

    private val editViewModel by viewModels<Step2ViewModel> { JoinUsViewModelFactory() }

    @SuppressLint("SetTextI18n")
    override fun initViews() {
        super.initViews()
        binding.etNameInput.setMaxLength(PROFILE_NICKNAME_MAX_LENGTH)
        binding.etNameInput.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
            ) {
            }

            override fun afterTextChanged(s: Editable?) {
                val name = s?.toString()
                binding.tvInputLength.text = "${name?.length ?: 0}/${PROFILE_NICKNAME_MAX_LENGTH}"
                editViewModel.setNickName(name)
            }
        })
        val nickName = editViewModel.getEditUserInfo().nickname
        binding.etNameInput.setText(nickName)
        binding.tvInputLength.text = "${nickName?.length ?: 0}/${PROFILE_NICKNAME_MAX_LENGTH}"
    }

    override fun observeViewModel() {
        super.observeViewModel()
        editViewModel.editUserInfoLD.observe(viewLifecycleOwner) {
            if (binding.etNameInput.text.isNullOrEmpty()) {
                binding.etNameInput.setText(it.nickname)
            }
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        binding.etNameInput.clearFocus()
        QMUIKeyboardHelper.hideKeyboard(binding.etNameInput)
    }

}