package com.develop.auth.ui

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.common.API_TOKEN
import com.develop.food.base.common.CURRENT_USER_ID_TAG
import com.develop.food.base.common.LOGIN_TAG
import com.develop.food.base.common.RECORD_ACCOUNT
import com.develop.food.base.common.RECORD_PASSWORD
import com.develop.food.base.event.FinishAtyEvent
import com.develop.food.base.ext.text_color
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.MmkvUtils
import com.develop.food.base.utils.dimenRes
import com.develop.food.base.utils.setVisible
import com.develop.food.base.widgets.CancelConfirmDialog
import org.greenrobot.eventbus.EventBus

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 = when (index) {
                    0 -> {
                        0
                    }

                    1 -> {
                        18
                    }

                    2 -> {
                        20
                    }

                    else -> {
                        index + 18
                    }
                }
                binding.tvChooseAge.text = selectAge.toString()
                binding.tvChooseAge.text_color = R.color.register_edit_color
            }.show()
        }
        binding.tvChooseSex.setOnClickListener {
            GenderSelectDialog {
                selectGender = if (it) 2 else 1
                if (selectGender == 2) {
                    binding.tvChooseSex.text = getString(R.string.male)
                } else {
                    binding.tvChooseSex.text = getString(R.string.female)
                }
                binding.tvChooseSex.text_color = R.color.register_edit_color
            }.showDialog(parentFragmentManager, "gender")
        }
        binding.tvSave.setOnClickListener {
            saveProfile(
                binding.etNickname.text.toString(),
                selectAge,
                selectGender,
                viewModel.chooseAvatar.value ?: 0
            )
        }
        binding.tvSkipForNow.setOnClickListener {
            if (binding.tvSkipForNow.text == getString(R.string.sign_out)) {
                EventBus.getDefault().post(FinishAtyEvent())
                FoodDataProvider.getUserDatabase().userInfoDao()
                    .deleteUserInfoByUserId(CURRENT_USER_ID)
                MmkvUtils.save(LOGIN_TAG, false)
                MmkvUtils.clear(API_TOKEN)
                MmkvUtils.save(CURRENT_USER_ID_TAG, 0)
                FoodDataProvider.getUserDatabase().userInfoDao().deleteAllUserInfo()
                parentFragmentManager.beginTransaction()
                    .replace(R.id.fl_container, MemberLoginFragment()).commitAllowingStateLoss()
            } else {
                navigateTo(Screens.Main.ENTRANCE_CHOSEN)
            }

        }

        val commonDialog = CancelConfirmDialog()
        commonDialog.title = getString(R.string.delete_account_ask)
        commonDialog.onDialogClickListener =
            object : CancelConfirmDialog.OnDialogClickListener {
                override fun onConfirm() {
                    viewModel.cancelAccount().observe(viewLifecycleOwner) {
                        EventBus.getDefault().post(FinishAtyEvent())
                        FoodDataProvider.getUserDatabase().userInfoDao()
                            .deleteUserInfoByUserId(CURRENT_USER_ID)
                        val saveToken: String? = null
                        MmkvUtils.save(API_TOKEN, saveToken)
                        MmkvUtils.save(LOGIN_TAG, false)
                        MmkvUtils.save(CURRENT_USER_ID_TAG, 0)
                        MmkvUtils.save(RECORD_ACCOUNT, "")
                        MmkvUtils.save(RECORD_PASSWORD, "")
                        FoodDataProvider.getUserDatabase().userInfoDao().deleteAllUserInfo()
                        parentFragmentManager.beginTransaction()
                            .replace(R.id.fl_container, MemberLoginFragment()).commitAllowingStateLoss()
                    }

                }

                override fun onCancel() {

                }
            }
        binding.tvDestroyAccount.setOnClickListener {
                commonDialog.showDialog(childFragmentManager,"deleteCommonDialog")
        }
        userInfoLiveData.observe(viewLifecycleOwner) {
            it?.apply {
                selectAge = userAge
                selectGender = userGender?.toInt() ?: 2
                binding.etNickname.setText(userName ?: "")
                binding.tvChooseAge.text = userAge.toString()
                binding.tvChooseSex.text_color = R.color.register_edit_color
                binding.tvChooseAge.text_color = R.color.register_edit_color
                if (selectGender == 2) {
                    binding.tvChooseSex.text = getString(R.string.male)
                } else {
                    binding.tvChooseSex.text = getString(R.string.female)
                }
                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 = getString(R.string.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) {
        val userInfo = UserInfo(
            user.id.toLong(), user.nickname.toString(), user.portrait, user.gender, user.age
        )
        MmkvUtils.save(CURRENT_USER_ID_TAG, user.id.toLong())
        FoodDataProvider.getUserDatabase().userInfoDao().updateUserInfo(userInfo)
    }

    private fun queryUserInfo() {
        FoodDataProvider.getUserDatabase().runInTransaction {
            val userId = MmkvUtils.getLong(CURRENT_USER_ID_TAG)
            val userInfo =
                FoodDataProvider.getUserDatabase().userInfoDao().queryUserInfoByUserId(userId)
            userInfoLiveData.postValue(userInfo)
        }
    }
}