package uz.mobiuz.mobiservice.dev.ui.home

import android.os.Bundle
import android.view.View
import android.widget.FrameLayout
import android.widget.LinearLayout
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import uz.mobiuz.mobiservice.dev.MainViewModel
import uz.mobiuz.mobiservice.dev.R
import uz.mobiuz.mobiservice.dev.databinding.FragmentMotionBinding
import uz.mobiuz.mobiservice.dev.model.SharedPref
import uz.mobiuz.mobiservice.dev.network.model.Customer
import uz.mobiuz.mobiservice.dev.ui.base.BaseFragment
import uz.mobiuz.mobiservice.dev.utils.extensions.showMessage
import javax.inject.Inject

@AndroidEntryPoint
class MotionFragment : BaseFragment(R.layout.fragment_motion) {

    @Inject
    lateinit var pref: SharedPref

    private var _bn: FragmentMotionBinding? = 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 jobAutoSlide: Job? = null
    private var jobToMatch: Job? = null

    private var customer: Customer? = null
    private var overScroll = 0
    private val sliderAdapter = SliderAdapter()
    private var lastUpdateTime = 0L
    private lateinit var matchParam: FrameLayout.LayoutParams
    private lateinit var changedParam: FrameLayout.LayoutParams
    private val navController: NavController by lazy(LazyThreadSafetyMode.NONE) { NavHostFragment.findNavController(this) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mainViewModel = ViewModelProvider(requireActivity())[MainViewModel::class.java]
        viewModel.mainIndex()
        viewModel.mainRoaming()
        matchParam = FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        changedParam = FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        _bn = FragmentMotionBinding.bind(view)
        isProgressing = true
        requireActivity().window.decorView.systemUiVisibility = View.VISIBLE
        setUpUI()
        collects()

    }

    override fun setUpUI() {

        bn.btnMenu.setOnClickListener {
            showMessage("click")
        }

//        bn.apply {
//            slider.adapter = sliderAdapter
//
//            sliderAdapter.setOnClickListener {
//                pref.isShowPin = false
//                val uri = Uri.parse(it.url)
//                val intent = Intent(Intent.ACTION_VIEW)
//                intent.data = uri
//                startActivity(intent)
//            }
//
//            TabLayoutMediator(tabIndicator, slider) { _, _ -> }.attach()
//
//            slider.offscreenPageLimit = 3
//            slider.getChildAt(0).overScrollMode = RecyclerView.OVER_SCROLL_NEVER
//
//            btnAddSum.setOnClickListener {
//                pref.isShowPin = false
//                if (checkInternet()) {
//                    navController.navigate(R.id.billingFragment)
//                }
//
//            }
//
//            val number = pref.userPhone.customMasketHome().replace("-", " ")
//            txtMyNumber.text = number
//            toolbarMyNumber.text = number
//
//            toolbar.setNavigationOnClickListener {
//                mainViewModel.openDrawer(System.currentTimeMillis())
//            }
//
//            bounceScrollView.setOnOverScrollListener { fromStart, overScrolledDistance ->
//                if (!fromStart) {
//                    lastUpdateTime = System.currentTimeMillis()
//                }
//                if (fromStart && overScrolledDistance > 140.52632 && (lastUpdateTime < System.currentTimeMillis() - 1000)) {
//
//                    if (checkInternet() && !isProgressing) {
//                        viewModel.mainIndex()
//                        vibrate(requireContext())
//                    }
//                    lastUpdateTime = System.currentTimeMillis()
//                }
//
//                if (fromStart) {
//                    changedParam.width = homeImage.width + (overScrolledDistance - overScroll)
//                    changedParam.height = homeImage.height + (overScrolledDistance - overScroll)
//                    homeImage.layoutParams = changedParam
//                } else {
//                    changedParam.width = homeImage.width - (overScroll - overScrolledDistance)
//                    changedParam.height = homeImage.height - (overScroll - overScrolledDistance)
//                    homeImage.layoutParams = changedParam
//                    changeToParam()
//                }
//                overScroll = overScrolledDistance
//
//
//            }
//
//            bounceScrollView.setOnScrollListener { _, scrollY ->
//                if (scrollY < 100) {
//                    toolbarInsideLayout.isVisible = false
//                    topDiv.setBackgroundColor(Color.TRANSPARENT)
//                    toolbar.setBackgroundColor(Color.TRANSPARENT)
//                }
//                if (scrollY > 20) {
//                    toolbar.setBackgroundColor(getColorCompat(R.color.primary100))
//                    topDiv.setBackgroundColor(getColorCompat(R.color.primary100))
//                }
//                if (scrollY > 90) {
//                    toolbarInsideLayout.isVisible = true
//                }
//            }
//        }
    }


    override fun collects() {
//        viewLifecycleOwner.lifecycleScope.launchWhenStarted {
//            viewModel.mainIndexUiState.collect {
//                when (it) {
//                    is UiStateObject.SUCCESS -> {
//                        bn.lottie.isVisible = false
//                        isProgressing = false
//                        customer = it.data
//                        loadData()
//                        showProgressDialog(false)
//                    }
//                    is UiStateObject.ERROR -> {
//                        isProgressing = false
//                        showProgressDialog(false)
//                        bn.lottie.isVisible = false
//                    }
//                    is UiStateObject.LOADING -> {
//                        bn.lottie.isVisible = true
//                        isProgressing = true
//                    }
//                    else -> Unit
//                }
//            }
//        }
//
//        viewLifecycleOwner.lifecycleScope.launchWhenStarted {
//            viewModel.mainRoamingUiState.collect {
//                when (it) {
//                    is UiStateObject.SUCCESS -> {
//                        showProgressDialog(false)
//                        bn.cardRoaming.isVisible = it.data.name != null
//                        bn.txtRoaming.text = it.data.name ?: ""
//                    }
//                    is UiStateObject.ERROR -> {
//                        showProgressDialog(false)
//                        bn.cardRoaming.isVisible = false
//                    }
//                    is UiStateObject.LOADING -> {
//                        bn.cardRoaming.isVisible = false
//                    }
//                    else -> Unit
//                }
//            }
//        }
    }

//    @SuppressLint("SetTextI18n")
//    private fun loadData() {
//        try {
//            sliderAdapter.submitList(customer?.events ?: emptyList())
//            customer?.customer?.info?.let {
//                bn.apply {
//
//                    txtBalance.text = "${it.balance?.amount?.toMoneyFormat()} ${it.balance?.currency}"
//                    pref.userBirthday = customer?.customer?.date_of_birth ?: ""
//                    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"
//
//                        txtTarif.text = customer?.customer?.tariff?.name
//                        val priceTariff = customer?.customer?.tariff?.total_price ?: 0
//                        if (priceTariff > 0) {
//                            txtSumTariff.text = getString(R.string.sum_month, priceTariff.toMoneyFormat())
//                        }
//
//                        txtTarifTo.text = customer?.customer?.tariff?.next_tariffication_date
//
//                        txtCountSms.text = it.ITEM?.value?.toMoneyFormat() ?: "0"
//                        txtTypeSms.text = it.ITEM?.unit ?: "sms"
//                    }
//                    mainViewModel.setUserName(customer?.customer?.name ?: "Unnamed User")
//                }
//            }
//        } catch (e: Exception) {
////            showSnackMessage(it.message)
//        }
//    }

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

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

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