package com.mobiuz.app.dev.ui.home

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import com.mobiuz.app.R
import com.mobiuz.app.databinding.FragmentHomeBinding
import com.mobiuz.app.dev.MainViewModel
import com.mobiuz.app.dev.model.SharedPref
import com.mobiuz.app.dev.network.model.Customer
import com.mobiuz.app.dev.network.model.UiStateObject
import com.mobiuz.app.dev.ui.base.BaseFragment
import com.mobiuz.app.dev.utils.extensions.*
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import me.everything.android.ui.overscroll.OverScrollDecoratorHelper
import javax.inject.Inject


@AndroidEntryPoint
class HomeFragment : BaseFragment(R.layout.fragment_home) {

    @Inject
    lateinit var pref: SharedPref

    private var _bn: FragmentHomeBinding? = null
    private val bn get() = _bn ?: throw NullPointerException("cannot inflate")
    private val viewModel: HomeViewModel by viewModels()
    private lateinit var mainViewModel: MainViewModel
    private var isProgressing = false
    private var isFirstProgressing = true
    private val navController: NavController by lazy(LazyThreadSafetyMode.NONE) { NavHostFragment.findNavController(this) }

    private var customer: Customer? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mainViewModel = ViewModelProvider(requireActivity())[MainViewModel::class.java]
        viewModel.mainIndex()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        _bn = FragmentHomeBinding.bind(view)
        val window = requireActivity().window.decorView
        window.systemUiVisibility = View.VISIBLE

        setUpUI()
        collects()

    }

    override fun setUpUI() {

        bn.apply {
            btnAddSum.setOnClickListener {
                navController.navigate(R.id.billingFragment)
            }
            toolbar.setNavigationOnClickListener {
                mainViewModel.mainIndex(System.currentTimeMillis())
            }

            scrollView.viewTreeObserver.addOnScrollChangedListener {


                if (scrollView.scrollY < 100) {
                    toolbarInsideLayout.isVisible = false
                    topDiv.setBackgroundColor(Color.TRANSPARENT)
                    toolbar.setBackgroundColor(Color.TRANSPARENT)
                }
                if (scrollView.scrollY > 20) {
                    toolbar.setBackgroundColor(getColorCompat(R.color.primary100))
                    topDiv.setBackgroundColor(getColorCompat(R.color.primary100))
                }
                if (scrollView.scrollY > 100) {
                    toolbarInsideLayout.isVisible = true
                }


            }

            val decor = OverScrollDecoratorHelper.setUpOverScroll(scrollView)

            decor.setOverScrollUpdateListener { _, _, offset ->
                if (offset > 150.52632) {
                    if (!isProgressing) {
                        vibrate(requireContext())
                        viewModel.mainIndex()
                    }
                }

                if (offset < 1.0) {
                    lottie.isVisible = false
                }
            }
        }
    }

    override fun collects() {
        viewLifecycleOwner.lifecycleScope.launchWhenStarted {
            viewModel.mainIndexUiState.collect {
                when (it) {
                    is UiStateObject.SUCCESS -> {
                        isProgressing = false
                        showProgressDialog(false)
                        bn.lottie.isVisible = false
                        isFirstProgressing = false
                        customer = it.data
                        loadData()
                    }
                    is UiStateObject.ERROR -> {
                        isProgressing = false
                        isFirstProgressing = false
                        showProgressDialog(false)
                        bn.lottie.isVisible = false
                    }
                    is UiStateObject.LOADING -> {
                        isProgressing = true
                        if (isFirstProgressing) showProgressDialog(true)
                        isFirstProgressing = false
                        bn.lottie.isVisible = true
                    }
                    else -> Unit
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun loadData() {
        try {
            customer?.customer?.info?.let {
                bn.apply {
                    txtBalance.text = "${it.balance?.amount?.toMoneyFormat()} ${it.balance?.currency}"
                    it.counters.let {
                        txtCountMb.text = it?.BYTE?.value?.toMoneyFormat() ?: "0"
                        txtTypeMb.text = it?.BYTE?.unit ?: "mb"

                        txtCountMinut.text = it?.SECOND?.value?.toMoneyFormat() ?: "0"
                        txtTypeMinut.text = it?.SECOND?.unit ?: "min"

                        txtCountSms.text = it?.ITEM?.value?.toMoneyFormat() ?: "0"
                        txtTypeSms.text = it?.ITEM?.unit ?: "sms"
                    }
                    mainViewModel.setUserName(customer?.customer?.name ?: "Unnamed User")
                    txtTarif.text = customer?.customer?.tarifi?.name ?: getString(R.string.my_tarif)
                    txtMyNumber.text = pref.userPhone.customMasketHome().replace("-", " ")
                    toolbarMyNumber.text = pref.userPhone.customMasketHome().replace("-", " ")
                }
            }
        } catch (e: Exception) {
//            showSnackMessage(it.message)
        }
    }

    override fun onResume() {
        super.onResume()
        mainViewModel.bottomSheet(true)
        mainViewModel.swipeDrawer(true)
        customLog("onResume")
    }

    override fun onStop() {
        super.onStop()
        mainViewModel.swipeDrawer(false)
    }

    override fun onDestroy() {
        _bn = null
        super.onDestroy()
    }
}