package com.adealink.weparty.profile.edit.dialog

import android.annotation.SuppressLint
import android.text.Editable
import android.text.TextWatcher
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.text.setMaxLength
import com.adealink.weparty.commonui.widget.KeyboardBottomDialogFragment
import com.adealink.weparty.constant.PROFILE_INTRODUCTION_MAX_LENGTH
import com.adealink.weparty.profile.R
import com.adealink.weparty.profile.databinding.DialogEditIntroBinding
import com.adealink.weparty.util.QMUIKeyboardHelper

class EditIntroDialog : KeyboardBottomDialogFragment(R.layout.dialog_edit_intro) {

    private val binding by viewBinding(DialogEditIntroBinding::bind)
    private var callback: IEditIntroCallback? = null

    private var intro: String? = null

    fun setCallback(callback: IEditIntroCallback?) {
        this.callback = callback
    }

    fun setIntro(intro: String?) {
        this.intro = intro
    }

    @SuppressLint("SetTextI18n")
    override fun initViews() {
        super.initViews()
        binding.etInput.setText(intro)
        binding.etInput.setMaxLength(PROFILE_INTRODUCTION_MAX_LENGTH)
        binding.etInput.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 length = s?.length ?: 0
                binding.tvInputCount.text = "${length}/${PROFILE_INTRODUCTION_MAX_LENGTH}"
            }
        })
        binding.tvInputCount.text =
            "${binding.etInput.text?.length ?: 0}/${PROFILE_INTRODUCTION_MAX_LENGTH}"
        binding.btnSave.onClick {
            save()
        }

        QMUIKeyboardHelper.showKeyboard(binding.etInput, true)
        binding.etInput.requestFocus()
    }

    private fun save() {
        val intro = binding.etInput.text?.toString()?.trim()
        callback?.onEditIntro(intro)
        dismiss()
    }

//    override fun onKeyboardChange(isShow: Boolean, keyboardHeight: Int) {
//        if (isShow) {
//            binding.btnSave.gone()
//        } else {
//            binding.btnSave.show()
//        }
//    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding.etInput.clearFocus()
        QMUIKeyboardHelper.hideKeyboard(binding.etInput)
    }


    interface IEditIntroCallback {
        fun onEditIntro(intro: String?)
    }


}