package com.adealink.weparty.joinus.step3

import android.view.KeyEvent
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.FragmentJoinUsStep3Binding
import com.adealink.weparty.joinus.step3.data.Step3Page
import com.adealink.weparty.joinus.step3.page.ChooseSkillFragment
import com.adealink.weparty.joinus.step3.page.SKillFormFragment
import com.adealink.weparty.joinus.step3.viewmodel.Step3ViewModel

class JoinUsStep3Fragment : BaseFragment(R.layout.fragment_join_us_step_3) {

    private val binding by viewBinding(FragmentJoinUsStep3Binding::bind)

    private val step3ViewModel by viewModels<Step3ViewModel>()

    override fun loadData() {
        super.loadData()
        step3ViewModel.showPage(Step3Page.CHOOSE_SKILL)
    }

    override fun observeViewModel() {
        super.observeViewModel()
        step3ViewModel.pageLD.observe(viewLifecycleOwner) { page ->
            when (page) {
                Step3Page.CHOOSE_SKILL -> {
                    inflateChooseSkill()
                }

                Step3Page.FILL_FORM -> {
                    inflateFillForm()
                }
            }
        }
    }

    private fun inflateChooseSkill() {
        val fragment = childFragmentManager.findFragmentByTag(Step3Page.CHOOSE_SKILL.page)
        if (fragment != null && fragment.isAdded) {
            return
        }
        childFragmentManager.beginTransaction()
            .replace(binding.flContent.id, ChooseSkillFragment(), Step3Page.CHOOSE_SKILL.page)
            .commitAllowingStateLoss()
    }

    private fun inflateFillForm() {
        val fragment = childFragmentManager.findFragmentByTag(Step3Page.FILL_FORM.page)
        if (fragment != null && fragment.isAdded) {
            return
        }
        childFragmentManager.beginTransaction()
            .replace(binding.flContent.id, SKillFormFragment(), Step3Page.FILL_FORM.page)
            .commitAllowingStateLoss()
    }

    override fun onBackPressed(): Boolean {
        if (!isViewBindingValid()) {
            return false
        }
        if (step3ViewModel.pageLD.value == Step3Page.FILL_FORM) {
            step3ViewModel.showPage(Step3Page.CHOOSE_SKILL)
            return true
        }
        return super.onBackPressed()
    }

}