package com.develop.auth.ui

import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.lifecycle.MutableLiveData
import com.develop.auth.R
import com.develop.auth.databinding.FragmentMemberProfileBinding
import com.develop.auth.viewmodel.MemberViewModel
import com.develop.base.ext.navigateTo
import com.develop.base.ext.resId2Dimension
import com.develop.base.ext.setVisible
import com.develop.base.mvvm.BaseBVMFragment
import com.develop.base.util.MMkvUtils
import com.develop.base.util.ThreadUtils
import com.develop.common.data_repo.FoodDataProvider
import com.develop.common.data_repo.db.entity.UserInfo
import com.develop.common.data_repo.net.model.response.User
import com.develop.common.dialog.AgeSelectDialog
import com.develop.common.dialog.GenderSelectDialog
import com.develop.common.router.Screens
import com.develop.common.tag.API_TOKEN
import com.develop.common.tag.LOGIN_TAG
import com.develop.common.ui.CommonBVMFragment

class MemberProfileFragment : CommonBVMFragment<FragmentMemberProfileBinding, MemberViewModel>() {

    private var selectAge = 0
    private var selectGender = 2

    override fun createViewBinding(
        inflater: LayoutInflater, container: ViewGroup?
    ): FragmentMemberProfileBinding {
        return FragmentMemberProfileBinding.inflate(inflater, container, false)
    }

    override fun onPostCreateView() {
        super.onPostCreateView()
        viewModel.queryUserInfo()
        binding.tvChooseAge.setOnClickListener {
            AgeSelectDialog(hostActivity) { index, change ->
                selectAge = index + 20
                binding.tvChooseAge.text = selectAge.toString()
                binding.tvChooseAge.setTextColor(Color.BLACK)
            }.show()
        }
        binding.ivMember.setOnClickListener {
            UserIconSelectDialog(viewModel).show(childFragmentManager, "UserIcon")
        }
        binding.tvChooseSex.setOnClickListener {
            GenderSelectDialog {
                selectGender = if (it) 2 else 1
                if (selectGender == 2) {
                    binding.tvChooseSex.text = "Male"
                } else {
                    binding.tvChooseSex.text = "Female"
                }
                binding.tvChooseSex.setTextColor(Color.BLACK)
            }.show(parentFragmentManager, "gender")
        }
        binding.tvSave.setOnClickListener {
            saveProfile(
                binding.etNickname.text.toString(),
                selectAge,
                selectGender,
                viewModel.chooseAvatar.value ?: 0
            )
        }
        binding.tvSkipForNow.setOnClickListener {
            if (viewModel.enterFromHome) {
                val saveToken: String? = null
                MMkvUtils.save(API_TOKEN, saveToken)
                MMkvUtils.save(LOGIN_TAG, false)
                FoodDataProvider.getUserDatabase().userInfoDao().deleteAllUserInfo()
                parentFragmentManager
                    .beginTransaction()
                    .replace(R.id.fl_container, MemberLoginFragment())
                    .commitAllowingStateLoss()
            } else {
                navigateTo(Screens.Main.ENTRANCE_CHOSEN)
            }
        }
        if (viewModel.enterFromHome) {
            binding.tvSkipForNow.text = "Sign out"
        }
        viewModel.apply {
            userInfoLiveData.observe(viewLifecycleOwner) {
                it?.apply {
                    selectAge = userAge
                    selectGender = userGender?.toInt() ?: 2
                    binding.etNickname.setText(userName ?: "")
                    viewModel.chooseAvatar.value = userAvatar?.toInt()
                    if (selectGender == 2) {
                        binding.tvChooseSex.text = "Male"
                        binding.tvChooseSex.setTextColor(Color.BLACK)
                    } else if (selectGender == 1) {
                        binding.tvChooseSex.text = "Female"
                        binding.tvChooseSex.setTextColor(Color.BLACK)
                    }
                    if (selectAge > 0) {
                        binding.tvChooseAge.text = selectAge.toString()
                        binding.tvChooseAge.setTextColor(Color.BLACK)
                    }
                }
            }
            perfectInfoLiveData.observe(viewLifecycleOwner) {
                dismissPlainDialog()
                it.msg?.apply {
                    showToast(this)
                }
                if (it.success) {
                    navigateTo(Screens.Main.ENTRANCE_CHOSEN)
                    hostActivity.finish()
                }
            }
            viewModel.chooseAvatar.observe(viewLifecycleOwner) {
                val icons = listOf(
                    com.develop.common.R.drawable.ic_icon1,
                    com.develop.common.R.drawable.ic_icon2,
                    com.develop.common.R.drawable.ic_icon3,
                    com.develop.common.R.drawable.ic_icon4,
                    com.develop.common.R.drawable.ic_icon5,
                    com.develop.common.R.drawable.ic_icon6
                )
                val chooseIcon = icons.getOrNull(it ?: 0) ?: com.develop.common.R.drawable.ic_icon1
                binding.ivMember.setImageResource(chooseIcon)
            }
        }
    }

    private fun saveProfile(
        nickname: String?, age: Int, sex: Int, portrait: Int
    ) {
        if (nickname.isNullOrEmpty()) {
            showToast("Please fill in nickname")
            return
        }
        if (age == 0) {
            showToast("Please fill in age")
            return
        }
        showPlainDialog(true)
        viewModel.perfectInfo(nickname, sex.toString(), portrait.toString(), age.toString())
    }

    override fun createViewModel(): MemberViewModel {
        return getViewModelOfActivity(MemberViewModel::class.java)
    }
}