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

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.net.Uri
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.facebook.shimmer.ShimmerFrameLayout
import com.google.android.material.tabs.TabLayoutMediator
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import uz.agr.sdk.coreui.extension.fadeIn
import uz.mobiuz.mobiservice.dev.MainViewModel
import uz.mobiuz.mobiservice.dev.R
import uz.mobiuz.mobiservice.dev.databinding.FragmentHomeBinding
import uz.mobiuz.mobiservice.dev.model.SharedPref
import uz.mobiuz.mobiservice.dev.network.model.Customer
import uz.mobiuz.mobiservice.dev.network.model.UiStateObject
import uz.mobiuz.mobiservice.dev.ui.base.BaseFragment
import uz.mobiuz.mobiservice.dev.utils.extensions.*
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 jobAutoSlide: 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 = FragmentHomeBinding.bind(view)
        requireActivity().window.decorView.systemUiVisibility = View.VISIBLE
        setUpUI()
        collects()

    }

    override fun setUpUI() {

        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 > 130.52632 && (lastUpdateTime < System.currentTimeMillis() - 1000)) {

                    if (checkInternet() && !isProgressing) {
                        viewModel.mainIndex()
                        vibrate(requireContext())
                    }
                    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
//                    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.shimmer.isVisible = false
                        bn.shimmer.stopShimmer()
                        bn.slider.isVisible = true
                        bn.tabIndicator.isVisible = true
                        bn.lottie.isVisible = false
                        isProgressing = false
                        customer = it.data
                        loadData()
                        showProgressDialog(false)
                    }
                    is UiStateObject.ERROR -> {

                        bn.shimmer.isVisible = false
                        bn.shimmer.stopShimmer()
                        bn.slider.isVisible = false
                        bn.tabIndicator.isVisible = false

                        isProgressing = false
                        showProgressDialog(false)
                        bn.lottie.isVisible = false
                    }
                    is UiStateObject.LOADING -> {
                        if (sliderAdapter.itemCount == 0){
                            bn.shimmer.isVisible = true
                            bn.shimmer.startShimmer()
                            bn.slider.isVisible = false
                            bn.tabIndicator.isVisible = false
                        }
                        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())
            bn.imagePlaceHolder.isVisible = customer?.events?.isEmpty() ?: false
            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()
    }
}