package com.adealink.weparty.joinus.step2.comp

import androidx.lifecycle.LifecycleOwner
import com.adealink.frame.mvvm.view.ViewComponent
import com.adealink.frame.mvvm.viewmodel.viewModels
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.BaseViewComponent
import com.adealink.weparty.commonui.widget.wheel.WheelDatePickerDialog
import com.adealink.weparty.joinus.databinding.LayoutJoinUsStep2EditBirthdayBinding
import com.adealink.weparty.joinus.step2.viewmodel.Step2ViewModel
import com.adealink.weparty.joinus.viewmodel.JoinUsViewModelFactory
import com.adealink.weparty.util.formatTimeTo
import com.adealink.weparty.util.get18YearsAgoTs

class EditBirthdayComp(
    lifecycleOwner: LifecycleOwner,
    private val binding: LayoutJoinUsStep2EditBirthdayBinding
) : BaseViewComponent(lifecycleOwner) {

    companion object {
        private const val TAG = "EditBirthdayComp"
    }

    private val editViewModel by viewModels<Step2ViewModel> { JoinUsViewModelFactory() }

    override fun initViews() {
        binding.clBirthday.onClick {
            showBirthdayDialog()
        }
    }

    override fun observeViewModel() {
        editViewModel.editUserInfoLD.observe(viewLifecycleOwner) {
            updateUI(it?.birthday)
        }
    }

    private fun updateUI(birthday: Long?) {
        if (birthday == null || birthday <= 0) {
            binding.tvBirthday.text = null
            return
        }
        binding.tvBirthday.text = formatTimeTo(birthday, "dd/MM/yyyy")
    }

    private fun showBirthdayDialog() {
        WheelDatePickerDialog.newInstance(
            initTimestamp = editViewModel.editUserInfoLD.value?.birthday,
            currentTimestamp = get18YearsAgoTs(),
        ).apply {
            selectBirthdayCallback = object : WheelDatePickerDialog.ISelectDateCallback {
                override fun onSelectComplete(timestamp: Long, timeStr: String) {
                    editViewModel.setBirthday(timestamp)
                }
            }
        }.show(
            fragmentManager, "editBirthday"
        )
    }

}