package com.develop.auth.ui

import android.text.InputFilter
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.EditText
import androidx.fragment.app.activityViewModels
import com.blankj.utilcode.util.KeyboardUtils
import com.develop.auth.R
import com.develop.auth.databinding.FragmentMemberLoginBinding
import com.develop.food.base.common.RECORD_ACCOUNT
import com.develop.food.base.common.RECORD_PASSWORD
import com.develop.food.base.router.Screens
import com.develop.food.base.router.navigateTo
import com.develop.food.base.ui.ViewBindingFragment
import com.develop.food.base.utils.MmkvUtils
import com.develop.food.base.utils.dimenRes
import java.util.regex.Matcher
import java.util.regex.Pattern


class MemberLoginFragment : ViewBindingFragment<FragmentMemberLoginBinding>(), KeyboardUtils.OnSoftInputChangedListener {

    private val viewModel by activityViewModels<MemberViewModel>()

    override fun createViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentMemberLoginBinding {
        return FragmentMemberLoginBinding.inflate(inflater, container, false)
    }

    override fun onPostCreateView() {
        binding.tvLogin.setOnClickListener {
            if (!checkInputs()) {
                showToast(getString(R.string.please_fill_in))
                return@setOnClickListener
            }
            executeLogin(
                binding.etEmailId.text.toString(),
                binding.etPassword.text.toString()
            )
        }
        binding.tvRegister.setOnClickListener {
            parentFragmentManager
                .beginTransaction()
                .replace(R.id.fl_container, MemberRegisterFragment())
                .commitAllowingStateLoss()
        }
        binding.tvForget.setOnClickListener {
            parentFragmentManager
                .beginTransaction()
                .replace(R.id.fl_container, MemberForgotFragment())
                .commitAllowingStateLoss()
        }
        binding.tvRemember.setOnClickListener {
            binding.cbRemember.isChecked = !binding.cbRemember.isChecked
            viewModel.loginRecord = binding.cbRemember.isChecked
        }
        binding.cbRemember.setOnCheckedChangeListener { _, isChecked ->
            viewModel.loginRecord = isChecked
            if (!isChecked) {
                MmkvUtils.save(RECORD_ACCOUNT, null as? String?)
                MmkvUtils.save(RECORD_PASSWORD, null as? String?)
            }
        }
        val saveAccount = MmkvUtils.getString(RECORD_ACCOUNT)
        val savePassword = MmkvUtils.getString(RECORD_PASSWORD)
        if (!saveAccount.isNullOrEmpty()
            && !savePassword.isNullOrEmpty()
        ) {
            binding.tvRemember.performClick()
            binding.etEmailId.setText(saveAccount)
            binding.etPassword.setText(savePassword)
        }
       // KeyboardUtils.registerSoftInputChangedListener(requireActivity(), this)
        setEditTextInhibitInputSpeChat(binding.etPassword)
    }


    private fun setEditTextInhibitInputSpeChat(editText: EditText) {
        val filter =
            InputFilter { source, start, end, dest, dstart, dend ->
                val speChat = "[-©®™℅¡¿¥£°^¢€%&-+()~`|•√π÷×¶∆`~!@#$%^=|':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？\"'_\\\\]"
                val pattern: Pattern = Pattern.compile(speChat)
                val matcher: Matcher = pattern.matcher(source.toString())
                if (matcher.find()) "" else null
            }
        editText.filters = arrayOf(filter)
    }
    override fun onSoftInputChanged(height: Int) {
        val flRoot = (activity as? MemberAuthActivity)?.getRootView() ?: return
        if (height == 0) {
            flRoot.translationY = 0f
            return
        }
        val location = IntArray(2)
        binding.etPassword.getLocationOnScreen(location)
        val viewBottom = requireActivity()
            .resources.displayMetrics
            .heightPixels - location[1]
        val requireDistance = dimenRes(R.dimen.convert_60px)
        if (viewBottom - height >= requireDistance) {
            return
        }
        val deltaHeight = height - viewBottom + requireDistance
        flRoot.translationY = -deltaHeight.toFloat()
        Log.d("SoftInput", "viewBottom:${viewBottom}, height:${height}")
    }

    private fun checkInputs(): Boolean {
        val inputEmailId = binding.etEmailId.text.toString()
        val inputPassword = binding.etPassword.text.toString()
        return inputEmailId.isNotEmpty() && inputPassword.isNotEmpty()
    }

    private fun executeLogin(emailId: String, password: String) {
        showDialog()
        viewModel.login(
            emailId, password
        ).observe(this) {
            dismissDialog()
            if (!it) {
                return@observe
            }
            navigateTo(Screens.Main.ENTRANCE_CHOSEN)
            hostActivity.finish()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        KeyboardUtils.unregisterSoftInputChangedListener(requireActivity().window)
    }

}