package com.develop.auth.ui

import android.graphics.Color
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.MutableLiveData
import com.develop.auth.R
import com.develop.auth.databinding.FragmentMemberProfileBinding
import com.develop.food.base.api.FoodRepository
import com.develop.food.base.api.response.User
import com.develop.food.base.http.Resource
import com.develop.food.base.repo.CURRENT_USER_ID
import com.develop.food.base.repo.FoodDataProvider
import com.develop.food.base.repo.entity.UserInfo
import com.develop.food.base.router.Screens
import com.develop.food.base.router.navigateTo
import com.develop.food.base.ui.ViewBindingFragment
import com.develop.food.base.utils.ThreadUtils
import com.develop.food.base.utils.dimenRes
import com.develop.food.base.utils.setVisible

class MemberProfileFragment : ViewBindingFragment<FragmentMemberProfileBinding>() {

    private var selectAge = 0
    private var selectGender = 2
    private val viewModel by activityViewModels<MemberViewModel>()

    private val userInfoLiveData by lazy {
        MutableLiveData<UserInfo>()
    }

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

    override fun onPostCreateView() {
        queryUserInfo()
        binding.tvChooseAge.setOnClickListener {
            AgeSelectDialog(hostActivity) { index, change ->
                selectAge = index + 20
                binding.tvChooseAge.text = selectAge.toString()
                binding.tvChooseAge.setTextColor(Color.BLACK)
            }.show()
        }
        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 {
            navigateTo(Screens.Main.ENTRANCE_CHOSEN)
        }
        binding.tvDestroyAccount.setOnClickListener {

        }
        userInfoLiveData.observe(viewLifecycleOwner) {
            it?.apply {
                selectAge = userAge
                selectGender = userGender?.toInt() ?: 2
                binding.etNickname.setText(userName ?: "")
                viewModel.chooseAvatar.value = userAvatar?.toInt()
            }
        }
        if (viewModel.enterFromHome) {
            (binding.tvTitle.layoutParams as ViewGroup.MarginLayoutParams).let {
                it.topMargin = dimenRes(R.dimen.convert_53px)
                binding.tvTitle.requestLayout()
            }
            (binding.tvSave.layoutParams as ViewGroup.MarginLayoutParams).let {
                it.topMargin = dimenRes(R.dimen.convert_101px)
                binding.tvSave.requestLayout()
            }
            (binding.tvSkipForNow.layoutParams as ViewGroup.MarginLayoutParams).let {
                it.topMargin = dimenRes(R.dimen.convert_16px)
                binding.tvSkipForNow.requestLayout()
            }
            binding.tvSkipForNow.text = "Sign out"
            binding.tvDestroyAccount.setVisible()
        }
    }

    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
        }
        showDialog(true)
        FoodRepository.perfectInfo(
            nickname, sex.toString(), portrait.toString(), age.toString()
        ).observe(viewLifecycleOwner) {
            if (it.status == Resource.Status.FAILURE) {
                showToast("Save failed")
                dismissDialog()
            } else if (it.status == Resource.Status.SUCCESS) {
                showToast("Save success")
                it.data?.user?.let { usr ->
                    saveDatabase(usr)
                }
                dismissDialog()
                navigateTo(Screens.Main.ENTRANCE_CHOSEN)
            }
        }
    }

    private fun saveDatabase(user: User) {
        ThreadUtils.runOnWorkThread({
            val userInfo = UserInfo(
                user.id.toLong(),
                user.account,
                user.portrait,
                user.gender,
                user.age
            )
            FoodDataProvider.getUserDatabase().userInfoDao().updateUserInfo(userInfo)
        })
    }

    private fun queryUserInfo() {
        FoodDataProvider.getUserDatabase().runInTransaction {
            val userInfo = FoodDataProvider.getUserDatabase().userInfoDao()
                .queryUserInfoByUserId(CURRENT_USER_ID)
            userInfoLiveData.postValue(userInfo)
        }
    }
}