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.BillingActivity
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.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.isActive
import java.text.SimpleDateFormat
import java.util.*
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 customer: Customer? = null
    private var overScroll = 0
    private val sliderAdapter = SliderAdapter()
    private var lastUpdateTime = 0L

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

    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 {

            slider.adapter = sliderAdapter

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

            jobAutoSlide = viewLifecycleOwner.lifecycleScope.launchWhenStarted {
                while (isActive) {
                    delay(4000)
                    if (slider.currentItem != tabIndicator.tabCount - 1) {
                        slider.currentItem = slider.currentItem + 1
                    } else {
                        slider.currentItem = 0
                    }
                }
            }
            slider.offscreenPageLimit = 3
            slider.getChildAt(0).overScrollMode = RecyclerView.OVER_SCROLL_NEVER

            btnAddSum.setOnClickListener {
                pref.isShowPin = false
                pref.blockedTime = System.currentTimeMillis()
                startActivity(Intent(requireContext(), BillingActivity::class.java))
            }

            txtMyNumber.text = pref.userPhone.customMasketHome().replace("-", " ")
            toolbarMyNumber.text = pref.userPhone.customMasketHome().replace("-", " ")

            toolbar.setNavigationOnClickListener {
                mainViewModel.openDrawer(System.currentTimeMillis())
            }

            val params0 = FrameLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
            val params = FrameLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)

            bounceScrollView.setOnOverScrollListener { fromStart, overScrolledDistance ->

//                customLog("fromStart:$fromStart,  overScrolledDistance:$overScrolledDistance")

                if (fromStart && overScrolledDistance > 140.52632 && (lastUpdateTime < System.currentTimeMillis() - 3000)) {
                    vibrate(requireContext())
                    viewModel.mainIndex()
                    lastUpdateTime = System.currentTimeMillis()
                }

                if (fromStart && overScroll < overScrolledDistance) {
                    params.width = homeImage.width + (overScrolledDistance - overScroll)
                    params.height = homeImage.height + (overScrolledDistance - overScroll)
                    homeImage.layoutParams = params
                } else {
                    params.width = homeImage.width - (overScroll - overScrolledDistance)
                    params.height = homeImage.height - (overScroll - overScrolledDistance)
                    homeImage.layoutParams = params0
                }
                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 -> {
                        showProgressDialog(false)
                        bn.lottie.isVisible = false
                        isFirstProgressing = false
                        customer = it.data
                        loadData()
                    }
                    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
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun loadData() {
        try {
            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"

                        txtSumTariff.text = getString(R.string.sum_month,it.SECOND?.value?.toMoneyFormat() ?: "0")
                        txtCountMinut.text = it.SECOND?.value?.toMoneyFormat() ?: "0"
                        txtTypeMinut.text = it.SECOND?.unit ?: "min"
                        txtTarif.text = it.SECOND?.name ?: "My tarif"

                        val strDate = it.SECOND?.date_to
                        val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm")
                        val date: Date = dateFormat.parse(strDate)
                        val d = SimpleDateFormat("dd MMMM")
                        txtTarifTo.text = d.format(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)
        customLog("onResume")
    }

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

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