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.activityViewModels
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 dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.collect
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 val mainViewModel: MainViewModel by activityViewModels()
    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)
        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() {

        with(bn) {
            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 {
                if (checkInternet()) {
                    navController.navigate(R.id.billingFragment)
                }

            }

            val number = pref.userPhone.customMasketHome().replace("-", " ")
            txtMyNumber.text = number
            toolbarMyNumber.text = number
            txtBalance.text = getString(R.string._0_uzs,"0")
            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
                }
                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 -> {
                        with(bn) {
                            shimmer.isVisible = false
                            shimmer.stopShimmer()
                            slider.isVisible = true
                            tabIndicator.isVisible = true
                            lottie.isVisible = false
                            isProgressing = false
                            customer = it.data
                            loadData()
                            showProgressDialog(false)
                        }

                    }
                    is UiStateObject.ERROR -> {
                        with(bn) {
                            shimmer.isVisible = false
                            shimmer.stopShimmer()
                            slider.isVisible = false
                            tabIndicator.isVisible = false
                            isProgressing = false
                            showProgressDialog(false)
                            lottie.isVisible = false
                        }

                    }
                    is UiStateObject.LOADING -> {
                        with(bn) {
                            if (sliderAdapter.itemCount == 0) {
                                shimmer.isVisible = true
                                shimmer.startShimmer()
                                slider.isVisible = false
                                tabIndicator.isVisible = false
                            }
                            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 = getString(R.string._0_uzs,it.balance?.amount?.toMoneyFormat() ?: "0")
                    pref.userBirthday = customer?.customer?.date_of_birth ?: ""
                    it.counters?.let {

                        txtCountMb.text = it.BYTE?.value?.toMoneyFormat() ?: "0"
                        txtCountMinut.text = it.SECOND?.value?.toMoneyFormat() ?: "0"
                        txtCountSms.text = it.ITEM?.value?.toMoneyFormat() ?: "0"

                        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

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