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_INTRODUCTION_MAX_LENGTH
import com.adealink.weparty.joinus.databinding.LayoutJoinUsStep2EditIntroductionBinding
import com.adealink.weparty.joinus.step2.viewmodel.Step2ViewModel
import com.adealink.weparty.joinus.viewmodel.JoinUsViewModelFactory
import com.adealink.weparty.util.QMUIKeyboardHelper

class EditIntroductionComp(
    lifecycleOwner: LifecycleOwner,
    private val binding: LayoutJoinUsStep2EditIntroductionBinding
) : BaseViewComponent(lifecycleOwner) {

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

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

    @SuppressLint("SetTextI18n")
    override fun initViews() {
        super.initViews()
        binding.etIntroInput.setMaxLength(PROFILE_INTRODUCTION_MAX_LENGTH)
        binding.etIntroInput.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 intro = s?.toString()
                val length = intro?.length ?: 0
                binding.tvInputLength.text = "${length}/${PROFILE_INTRODUCTION_MAX_LENGTH}"
                editViewModel.setIntro(intro)
            }
        })

        val intro = editViewModel.getEditUserInfo().intro
        binding.etIntroInput.setText(intro)
        binding.tvInputLength.text = "${intro?.length ?: 0}/${PROFILE_INTRODUCTION_MAX_LENGTH}"
    }

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

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

}