package com.adealink.weparty.joinus.step1

import androidx.fragment.app.viewModels
import com.adealink.frame.ext.isViewBindingValid
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.weparty.commonui.BaseFragment
import com.adealink.weparty.joinus.R
import com.adealink.weparty.joinus.databinding.FragmentJoinUsStep1Binding
import com.adealink.weparty.joinus.step1.data.Step1Page
import com.adealink.weparty.joinus.step1.page.InputPhoneFragment
import com.adealink.weparty.joinus.step1.page.InputVerifyFragment
import com.adealink.weparty.joinus.step1.viewmodel.Step1ViewModel

class JoinUsStep1Fragment : BaseFragment(R.layout.fragment_join_us_step_1) {

    private val binding by viewBinding(FragmentJoinUsStep1Binding::bind)

    private val step1ViewModel by viewModels<Step1ViewModel>()

    override fun loadData() {
        super.loadData()
        step1ViewModel.showPage(Step1Page.INPUT_PHONE)
    }

    override fun observeViewModel() {
        super.observeViewModel()
        step1ViewModel.pageLD.observe(viewLifecycleOwner) { page ->
            when (page) {
                Step1Page.INPUT_PHONE -> {
                    inflateInputPhone()
                }

                Step1Page.INPUT_VERIFY -> {
                    inflateInputVerify()
                }
            }
        }
    }

    private fun inflateInputPhone() {
        val fragment = childFragmentManager.findFragmentByTag(Step1Page.INPUT_PHONE.page)
        if (fragment != null && fragment.isAdded) {
            return
        }
        childFragmentManager.beginTransaction()
            .replace(binding.flContent.id, InputPhoneFragment(), Step1Page.INPUT_PHONE.page)
            .commitAllowingStateLoss()
    }

    private fun inflateInputVerify() {
        val fragment = childFragmentManager.findFragmentByTag(Step1Page.INPUT_VERIFY.page)
        if (fragment != null && fragment.isAdded) {
            return
        }
        childFragmentManager.beginTransaction()
            .replace(binding.flContent.id, InputVerifyFragment(), Step1Page.INPUT_VERIFY.page)
            .commitAllowingStateLoss()
    }

    override fun onBackPressed(): Boolean {
        if (!isViewBindingValid()) {
            return false
        }
        if (step1ViewModel.pageLD.value == Step1Page.INPUT_VERIFY) {
            step1ViewModel.showPage(Step1Page.INPUT_PHONE)
            return true
        }
        return super.onBackPressed()
    }

}