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

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.FrameLayout
import android.widget.LinearLayout
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 androidx.recyclerview.widget.RecyclerView
import com.google.android.material.tabs.TabLayoutMediator
import com.mobiuz.app.R
import com.mobiuz.app.databinding.FragmentHomeBinding
import com.mobiuz.app.dev.BillingFragment
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.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
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 isFirstProgressing = true
    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.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        _bn = FragmentHomeBinding.bind(view)

        requireActivity().window.decorView.systemUiVisibility = View.VISIBLE
        setUpUI()
        collects()

    }

    override fun setUpUI() {

        bn.apply {
            slider.adapter = sliderAdapter

            TabLayoutMediator(tabIndicator, slider) { _, _ -> }.attach()

//            lifecycleScope.launchWhenCreated {
//                repeat(10000000){
//                    delay(4000)
//                    if (slider.currentItem != tabIndicator.tabCount - 1) {
//                        slider.currentItem = slider.currentItem + 1
//                    } else {
//                        slider.currentItem = 0
//                    }
//                }
//            }


//            jobAutoSlide = viewLifecycleOwner.lifecycleScope.launchWhenStarted {
//                while (isActive) {
//
//                }
//            }
            slider.offscreenPageLimit = 3
            slider.getChildAt(0).overScrollMode = RecyclerView.OVER_SCROLL_NEVER

            btnAddSum.setOnClickListener {
                pref.isShowPin = false
                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() - 2000)) {
                    vibrate(requireContext())
                    viewModel.mainIndex()
                    lastUpdateTime = System.currentTimeMillis()
                }

                if (fromStart && overScroll < overScrolledDistance) {
                    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 = matchParam
                }
                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
                        isFirstProgressing = false
                        customer = it.data
                        loadData()
                        showProgressDialog(false)
                    }
                    is UiStateObject.ERROR -> {
                        isFirstProgressing = false
                        showProgressDialog(false)
                        bn.lottie.isVisible = false
                    }
                    is UiStateObject.LOADING -> {
                        if (isFirstProgressing) showProgressDialog(true)
                        else {
                            bn.lottie.isVisible = true
                            isFirstProgressing = false
                        }

                    }
                    else -> Unit
                }
            }
        }

        viewLifecycleOwner.lifecycleScope.launchWhenStarted {
            viewModel.mainRoamingUiState.collect {
                when (it) {
                    is UiStateObject.SUCCESS -> {
                        showProgressDialog(false)
                        bn.cardRoaming.isVisible = it.data.name != null
                    }
                    is UiStateObject.ERROR -> {
                        showProgressDialog(false)
                        bn.cardRoaming.isVisible = false
                    }
                    is UiStateObject.LOADING -> {
                        bn.cardRoaming.isVisible = false
                    }
                    else -> Unit
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun loadData() {
        try {
            customer?.customer?.info?.let {
                bn.apply {

//                    loadSum(it.balance?.amount?.toDouble(),it.balance?.currency)
                    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 total_price = customer?.customer?.tariff?.total_price ?: 0
                        if(total_price > 0){
                            txtSumTariff.text = getString(R.string.sum_month, total_price.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)
        }
    }

    private fun loadSum(amount:Double?, currency:String?){
        lifecycleScope.launchWhenCreated {
            var i = 0.0
           while (i < amount ?: 0.0){
               delay(50)
               i += 10000
               bn.txtBalance.text = "${i.toMoneyFormat()} $currency"
           }

        }
    }

    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()
    }
}