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

import android.os.Bundle
import android.view.View
import android.widget.FrameLayout
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.toast.util.showToast
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.module.profile.data.VoiceData
import com.adealink.weparty.module.widget.form.data.StringStepField
import com.adealink.weparty.module.widget.form.field.voice.VoiceWidgetData
import com.adealink.weparty.module.widget.form.field.voice.VoiceWidgetView
import com.adealink.weparty.module.widget.form.field.voice.VoiceWidgetView.OnRecordListener
import com.adealink.weparty.playmate.R
import com.adealink.weparty.playmate.databinding.FragmentPlaymateWelcomeAddVoiceBinding
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 WelcomeAddVoiceFragment : BaseFragment(R.layout.fragment_playmate_welcome_add_voice) {
    companion object {
        const val TAG = "WelcomeAddVoiceFragment"
    }

    private val binding by viewBinding(FragmentPlaymateWelcomeAddVoiceBinding::bind)

    private val pageViewModel by activityViewModels<WelcomePageViewModel>()
    private val welcomeViewModel by activityViewModels<WelcomeViewModel>()
    private lateinit var voiceView: VoiceWidgetView

    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.tvTitle.text = getCompatString(R.string.playmate_welcome_title_index, "")
        binding.btnSubmit.updateLayoutParams<ConstraintLayout.LayoutParams> {
            bottomMargin = activity.naviBarHeight() + 12.dp()
        }

        voiceView = VoiceWidgetView(binding.root.context)
        binding.vVoice.addView(
            voiceView, FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.WRAP_CONTENT
            )
        )
        voiceView.onViewCreated(this, VoiceWidgetData(StringStepField(null)))
        voiceView.setTopTitleVisible(false)
        voiceView.recordListener = object : OnRecordListener {
            override fun onRecordInfoChanged(voiceData: VoiceData?) {
                updateSubmitButton()
            }

            override fun onRecordStart() {
                updateSubmitButton()
            }

            override fun onRecordFinish(fail: Boolean) {
                updateSubmitButton()
            }
        }

        binding.btnSubmit.isEnabled = false
        binding.btnSubmit.onClick {
            submit()
        }
    }

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

            voiceView.setVoiceData(
                VoiceData(
                    url = data.voice,
                    path = null,
                    duration = data.voiceDuration?.toLong()
                )
            )

            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 isEditMode(): Boolean {
        val data = welcomeData
        return data != null && data.isVoice()
    }

    private fun updateSubmitButton() {
        if (!isViewBindingValid()) {
            return
        }
        if (isEditMode()) {
            val voiceData = voiceView.getVoiceData()
            binding.btnSubmit.isEnabled =
                welcomeData?.voice != voiceData?.url && voiceData?.isNull() == false
        } else {
            val voiceData = voiceView.getVoiceData()
            if (voiceData == null || voiceData.isNull()) {
                binding.btnSubmit.isEnabled = false
                return
            }
            binding.btnSubmit.isEnabled = true
        }
    }

    private fun submit() {
        val voiceData = voiceView.getVoiceData()
        if (voiceData == null || voiceData.isNull()) {
            showToast(R.string.playmate_welcome_add_voice_null)
            return
        }
        showLoading()
        welcomeViewModel.addVoiceWelcome(voiceView).observe(viewLifecycleOwner) { rlt ->
            dismissLoading()
            showToast(rlt)
            when (rlt) {
                is Rlt.Failed -> {
                    //Ntd.
                }

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

    private fun resubmit() {
        val data = welcomeData ?: return
        val voiceData = voiceView.getVoiceData()
        if (voiceData == null || voiceData.isNull()) {
            showToast(R.string.playmate_welcome_add_voice_null)
            return
        }
        if (data.voice == voiceData.url) {
            activity?.finish()
            return
        }
        showLoading()
        welcomeViewModel.updateVoice(data, voiceView).observe(viewLifecycleOwner) { rlt ->
            dismissLoading()
            showToast(rlt)
            when (rlt) {
                is Rlt.Failed -> {
                    //Ntd.
                }

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

}