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.mvvm.view.viewBinding
import com.adealink.frame.util.formatTime
import com.adealink.frame.util.onClick
import com.adealink.weparty.account.R
import com.adealink.weparty.account.databinding.FragmentRegisterCompleteUserinfoBinding
import com.adealink.weparty.account.register.Page
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.gone
import com.adealink.weparty.commonui.ext.onWindowInsets
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.commonui.toast.util.showToast
import com.adealink.weparty.commonui.widget.wheel.WheelDatePickerDialog
import com.adealink.weparty.util.TIME_FORMAT_DMY
import com.adealink.weparty.util.applyImmersive
import com.adealink.weparty.util.get18YearsAgoTs

class CompleteUserInfoFragment : BaseFragment(R.layout.fragment_register_complete_userinfo) {
    private val binding by viewBinding(FragmentRegisterCompleteUserinfoBinding::bind)
    private val editViewModel by activityViewModels<RegisterProfileViewModel> { AccountViewModelFactory() }

    override fun initViews() {
        super.initViews()
        fitWindow()
        activity.applyImmersive { top ->
            binding.topBar.updateLayoutParams<ConstraintLayout.LayoutParams> {
                topMargin = top
            }
        }
        binding.topBar.backCallback = {
            editViewModel.goPage(Page.SelectGender)
        }
        binding.ivAvatar.onClick {
            modifyAvatar()
        }
        binding.ivModifyAvatar.onClick {
            modifyAvatar()
        }
        binding.clBirthday.onClick {
            modifyBirthday()
        }
        binding.btnChangeName.onClick {
            randomNickName()
        }
        binding.btnNext.onClick {
            nextStep()
        }

        val editUserInfo = editViewModel.getEditUserInfo()
        if (editUserInfo.avatar?.isRemote() == true) {
            binding.ivAvatar.setImageUrl(editUserInfo.avatar?.url)
        } else if (editUserInfo.avatar?.isLocal() == true) {
            binding.ivAvatar.setImageURI(editUserInfo.avatar?.uri)
        } else {
            binding.ivAvatar.setImageUrl(null)
        }
        binding.etNameInput.setText(editUserInfo.nickname)

        val birthday = editUserInfo.birthday
        if (birthday != null && birthday > 0L) {
            binding.tvBirthday.text = formatTime(birthday, TIME_FORMAT_DMY)
        } else {
            val initBirthday = get18YearsAgoTs()
            editUserInfo.birthday = initBirthday
            binding.tvBirthday.text = formatTime(initBirthday, TIME_FORMAT_DMY)
        }
    }

    private fun fitWindow() {
        // 关键：只在需要的时候设置
        activity?.window?.fitSystemWindows(false)
        // 内容布局处理键盘
        val svContent = binding.svContent
        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)
            svContent.doOnPreDraw {
                svContent.smoothScrollTo(0, bottomInset)
            }
            insets
        }
    }

    override fun observeViewModel() {
        super.observeViewModel()
        editViewModel.editUserInfoLD.observe(viewLifecycleOwner) {
            if (it.avatar?.isRemote() == true) {
                binding.ivAvatar.setImageUrl(it.avatar?.url)
            } else if (it.avatar?.isLocal() == true) {
                binding.ivAvatar.setImageURI(it.avatar?.uri)
            } else {
                binding.ivAvatar.setImageUrl(null)
            }

            val birthday = it.birthday
            if (birthday != null && birthday > 0L) {
                binding.tvBirthday.text = formatTime(birthday, TIME_FORMAT_DMY)
            } else {
                binding.tvBirthday.text = null
            }
        }

        editViewModel.randomProfileLD.observe(viewLifecycleOwner) {
            if (it == null) {
                binding.btnChangeName.gone()
                return@observe
            }
            binding.btnChangeName.show()

            val avatar = editViewModel.getEditUserInfo().avatar
            if (avatar == null || avatar.isNull()) {
                editViewModel.setRandomAvatarUrl(
                    editViewModel.getNextRandomAvatar()
                )
            }

            if (binding.etNameInput.text.isNullOrEmpty()) {
                binding.etNameInput.setText(editViewModel.getNextRandomNickname())
            }
        }
    }

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

    private fun modifyBirthday() {
        WheelDatePickerDialog.newInstance(
            currentTimestamp = editViewModel.getEditUserInfo().birthday ?: get18YearsAgoTs(),
            confirmButtonText = getCompatString(R.string.account_register_next),
        ).apply {
            selectBirthdayCallback = object : WheelDatePickerDialog.ISelectDateCallback {
                override fun onSelectComplete(timestamp: Long, timeStr: String) {
                    editViewModel.setBirthday(timestamp)
                }
            }
        }.show(
            childFragmentManager, "modifyBirthday"
        )
    }

    private fun randomNickName() {
        editViewModel.setRandomAvatarUrl(editViewModel.getNextRandomAvatar())
        binding.etNameInput.setText(editViewModel.getNextRandomNickname())
    }

    private fun nextStep() {
        //头像不能为空
        val avatarData = editViewModel.getEditUserInfo().avatar
        if (avatarData == null || avatarData.isNull()) {
            showToast(R.string.account_register_avatar_is_null)
            return
        }

        //昵称不能为空
        val nickName = binding.etNameInput.text?.toString()?.trim()
        if (nickName.isNullOrEmpty()) {
            showToast(R.string.account_register_nickname_is_null)
            return
        }
        editViewModel.setNickName(nickName)

        //年龄不能为空
        val birthday = editViewModel.getEditUserInfo().birthday
        if (birthday == null || birthday <= 0) {
            showToast(R.string.account_register_birthday_is_null)
            return
        }
        editViewModel.setBirthday(birthday)
        editViewModel.goPage(Page.SelectCategory)
    }
}