package com.adealink.weparty.account.register.fragment

import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.doOnPreDraw
import androidx.core.view.updateLayoutParams
import androidx.core.view.updatePadding
import androidx.fragment.app.activityViewModels
import com.adealink.frame.aab.util.getCompatString
import com.adealink.frame.base.Rlt
import com.adealink.frame.base.fastLazy
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.util.formatTime
import com.adealink.frame.util.onClick
import com.adealink.frame.util.statusBarHeight
import com.adealink.weparty.account.R
import com.adealink.weparty.account.databinding.FragmentRegisterCompleteUserinfoBinding
import com.adealink.weparty.account.register.dialog.ModifyAvatarDialog
import com.adealink.weparty.account.register.viewmodel.RegisterProfileViewModel
import com.adealink.weparty.account.viewModel.AccountViewModelFactory
import com.adealink.weparty.commonui.BaseFragment
import com.adealink.weparty.commonui.ext.fitSystemWindows
import com.adealink.weparty.commonui.ext.onWindowInsets
import com.adealink.weparty.commonui.toast.util.showFailedToast
import com.adealink.weparty.commonui.toast.util.showToast
import com.adealink.weparty.commonui.widget.wheel.WheelDatePickerDialog
import com.adealink.weparty.module.profile.ProfileModule
import com.adealink.weparty.storage.AppPref

class CompleteUserInfoFragment : BaseFragment(R.layout.fragment_register_complete_userinfo) {
    private val binding by viewBinding(FragmentRegisterCompleteUserinfoBinding::bind)
    private val viewModel by activityViewModels<RegisterProfileViewModel> { AccountViewModelFactory() }
    private val profileViewModel by fastLazy { ProfileModule.getProfileViewModel(this) }
    override fun initViews() {
        super.initViews()
        binding.topBar.updateLayoutParams<ConstraintLayout.LayoutParams> {
            topMargin = activity.statusBarHeight()
        }
        binding.topBar.backCallback = {
            activity?.onBackPressed()
        }
        binding.ivAvatar.onClick {
            modifyAvatar()
        }
        binding.ivModifyAvatar.onClick {
            modifyAvatar()
        }
        binding.clBirthday.onClick {
            modifyBirthday()
        }
        binding.btnNext.onClick {
            nextStep()
        }

        fitWindow()
    }

    private fun fitWindow() {
        // 关键：只在需要的时候设置
        activity?.window?.fitSystemWindows(false)
        // 内容布局处理键盘
        binding.svContent.onWindowInsets { view, insets ->
            val ime = insets.getInsets(WindowInsetsCompat.Type.ime())
            val nav = insets.getInsets(WindowInsetsCompat.Type.navigationBars())

            // 键盘显示时使用键盘高度，否则使用导航栏高度
            val bottomInset = if (ime.bottom > 0) ime.bottom else nav.bottom
            view.updatePadding(bottom = bottomInset)
            binding.svContent.doOnPreDraw {
                binding.svContent.smoothScrollTo(0, bottomInset)
            }
            insets
        }
    }

    override fun observeViewModel() {
        super.observeViewModel()
        viewModel.avatarUriLD.observe(viewLifecycleOwner) {
            binding.ivAvatar.setImageURI(it)
        }
        viewModel.birthdayLD.observe(viewLifecycleOwner) {
            binding.tvBirthday.text = formatTime(it, "yyyy-MM-dd")
        }
    }

    private fun modifyAvatar() {
        ModifyAvatarDialog().show(
            childFragmentManager, "ModifyAvatarDialog"
        )
    }

    private fun modifyBirthday() {
        WheelDatePickerDialog.newInstance(
            confirmButtonText = getCompatString(R.string.account_register_next)
        ).apply {
            selectBirthdayCallback = object : WheelDatePickerDialog.ISelectDateCallback {
                override fun onSelectComplete(timestamp: Long, timeStr: String) {
                    viewModel.selectBirthday(timestamp)
                }
            }
        }.show(
            childFragmentManager, "modifyBirthday"
        )
    }

    private fun nextStep() {
        val nickName = binding.etNameInput.text?.toString()?.trim()
        if (nickName.isNullOrEmpty()) {
            showToast(R.string.account_register_nickname_is_null)
            return
        }
        showLoading()
        profileViewModel?.updateProfile(
            newAvatarPath = viewModel.avatarPath,
            newNickName = nickName,
            newGender = viewModel.gender?.gender,
            // TODO: 设置生日
//            newAge = viewModel.birthday?.toString()
        )?.observe(viewLifecycleOwner) { rlt ->
            dismissLoading()
            AppPref.needRegister = false
            when (rlt) {
                is Rlt.Failed -> {
                    showFailedToast(rlt)
                }

                is Rlt.Success<*> -> {
                    viewModel.notifyCompleteUserInfoFinish()
                }
            }
        }
    }
}