package com.adealink.weparty.playmate.saywelcome.fragment

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.activityViewModels
import com.adealink.frame.aab.util.getCompatString
import com.adealink.frame.base.Rlt
import com.adealink.frame.ext.isViewBindingValid
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.util.naviBarHeight
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.BaseFragment
import com.adealink.weparty.commonui.ext.dp
import com.adealink.weparty.commonui.ext.gone
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.commonui.text.setMaxLength
import com.adealink.weparty.commonui.toast.util.showToast
import com.adealink.weparty.constant.PLAYMATE_WELCOME_TEXT_MAX_LENGTH
import com.adealink.weparty.module.playmate.Playmate
import com.adealink.weparty.module.playmate.data.SayWelcomeData
import com.adealink.weparty.module.playmate.data.SayWelcomeStatus
import com.adealink.weparty.playmate.R
import com.adealink.weparty.playmate.databinding.FragmentPlaymateWelcomeAddTextBinding
import com.adealink.weparty.playmate.saywelcome.viewmodel.WelcomePageViewModel
import com.adealink.weparty.playmate.saywelcome.viewmodel.WelcomeViewModel
import com.adealink.weparty.util.parcelableExtra
import com.adealink.weparty.R as APP_R

class WelcomeAddTextFragment : BaseFragment(R.layout.fragment_playmate_welcome_add_text) {

    companion object {
        const val TAG = "WelcomeAddTextFragment"
    }

    private val binding by viewBinding(FragmentPlaymateWelcomeAddTextBinding::bind)

    private val pageViewModel by activityViewModels<WelcomePageViewModel>()

    private val welcomeViewModel by activityViewModels<WelcomeViewModel>()

    private var welcomeData: SayWelcomeData? = null

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        welcomeData = arguments?.parcelableExtra(
            Playmate.SayWelcomeSetting.EXTRA_WELCOME_DATA,
            SayWelcomeData::class.java
        )
        super.onViewCreated(view, savedInstanceState)
    }

    override fun initViews() {
        super.initViews()
        binding.btnSubmit.updateLayoutParams<ConstraintLayout.LayoutParams> {
            bottomMargin = activity.naviBarHeight() + 12.dp()
        }

        binding.tvTitle.text = getCompatString(R.string.playmate_welcome_title_index, "")
        binding.etInput.setMaxLength(PLAYMATE_WELCOME_TEXT_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?.trim()?.length ?: 0
                binding.tvInputLength.text = "${length}/${PLAYMATE_WELCOME_TEXT_MAX_LENGTH}"
                updateSubmitButton()
            }
        })
        binding.tvInputLength.text = "${(binding.tvInputLength.text?.length ?: 0)}/${PLAYMATE_WELCOME_TEXT_MAX_LENGTH}"
        binding.btnSubmit.isEnabled = false
        binding.btnSubmit.onClick {
            submit()
        }
    }

    override fun loadData() {
        super.loadData()
        val data = welcomeData
        if (data != null && data.isText()) {
            binding.tvTitle.text =
                getCompatString(R.string.playmate_welcome_title_index, data.itemPosition ?: "")

            binding.etInput.setText(data.text)

            if (SayWelcomeStatus.map(data.status) == SayWelcomeStatus.REJECT) {
                binding.vReject.root.show()
                binding.vReject.tvRejectReason.text = data.reviewReason
            } else {
                binding.vReject.root.gone()
            }

            binding.btnSubmit.text = getCompatString(APP_R.string.common_resubmit)
            binding.btnSubmit.onClick {
                resubmit()
            }
        }
    }

    private fun submit() {
        val inputText = binding.etInput.text?.toString()
        if (inputText.isNullOrEmpty()) {
            showToast(R.string.playmate_welcome_add_text_null)
            return
        }
        showLoading()
        welcomeViewModel.addWelcome(text = inputText).observe(viewLifecycleOwner) { rlt ->
            dismissLoading()
            showToast(rlt)
            when (rlt) {
                is Rlt.Failed -> {
                    //Ntd.
                }

                is Rlt.Success -> {
                    pageViewModel.afterSubmit()
                }
            }
        }
    }

    private fun isEditMode(): Boolean {
        val data = welcomeData
        return data != null && data.isText()
    }

    private fun updateSubmitButton() {
        if (!isViewBindingValid()) {
            return
        }
        if (isEditMode()) {
            val oldText = welcomeData?.text
            val newText = binding.etInput.text?.toString()
            binding.btnSubmit.isEnabled = oldText != newText && (newText?.trim()?.length ?: 0) > 0
        } else {
            val length = binding.etInput.text?.trim()?.length ?: 0
            binding.btnSubmit.isEnabled = length > 0
        }
    }

    private fun resubmit() {
        val data = welcomeData ?: return
        val inputText = binding.etInput.text?.toString()
        if (inputText.isNullOrEmpty()) {
            showToast(R.string.playmate_welcome_add_text_null)
            return
        }
        if (data.text == inputText) {
            activity?.finish()
            return
        }
        showLoading()
        welcomeViewModel.updateText(
            SayWelcomeData(
                data.id,
                data.type,
                data.status,
                text = inputText
            )
        ).observe(viewLifecycleOwner) { rlt ->
            dismissLoading()
            showToast(rlt)
            when (rlt) {
                is Rlt.Failed -> {
                    //Ntd.
                }

                is Rlt.Success -> {
                    pageViewModel.afterSubmit()
                }
            }
        }
    }

}