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.util.Log
import android.view.ScrollCaptureCallback
import android.view.View
import android.view.ViewTreeObserver
import androidx.core.view.GravityCompat
import androidx.core.view.isVisible
import androidx.core.widget.NestedScrollView
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.mobiuz.app.R
import com.mobiuz.app.databinding.FragmentHomeBinding
import com.mobiuz.app.dev.AuthActivity
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.ui.global.ButtonClick
import com.mobiuz.app.dev.utils.extensions.*
import dagger.hilt.android.AndroidEntryPoint
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 var customer: Customer? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel.mainIndex()
    }

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

        setUpUI()
        collects()

    }

    override fun setUpUI() {

        bn.apply {
            btnExit.setOnClickListener {
                showCustomExitDialog {
                    pref.setUserToken("")
                    pref.isRegistered = false
                    pref.pin_code = ""
                    val intent = Intent(requireContext(), AuthActivity::class.java)
                    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_TASK_ON_HOME
                    startActivity(intent)
                    requireActivity().finish()
                }
            }

            btnLanguage.setOnClickListener {

            }

            btnSafety.setOnClickListener {

            }
            btnSupport.setOnClickListener {

            }
        }


        bn.content.apply {
            toolbar.setNavigationOnClickListener {
                bn.drawerLayout.openDrawer(GravityCompat.START)
            }

            nestedScrollView.setOnScrollChangeListener(object : NestedScrollView.OnScrollChangeListener{
                override fun onScrollChange(v: NestedScrollView?, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) {
                    Log.e("SSS","scrollX_"+scrollX+"_scrollY_"+scrollY+"_oldScrollX_"+oldScrollX+"_oldScrollY_"+oldScrollY)

                    if(scrollY > 100){
                        toolbarInsideLayout.isVisible = true
//                        requireActivity().window.statusBarColor = Color.RED
//                        toolbar.setBackgroundColor(resources.getColor(R.color.primary100))
                    }

                    if(scrollY < 90){
                        toolbarInsideLayout.isVisible = false
//                        requireActivity().window.statusBarColor = Color.TRANSPARENT
//                        toolbar.setBackgroundColor(Color.TRANSPARENT)
                    }

                }
            })
        }
    }

    override fun collects() {
        viewLifecycleOwner.lifecycleScope.launchWhenStarted {
            viewModel.mainIndexUiState.collect {
                when (it) {
                    is UiStateObject.SUCCESS -> {
                        showProgressDialog(false)
                        customer = it.data
                        loadData()
                    }
                    is UiStateObject.ERROR -> {
                        showProgressDialog(false)
//                        showCustomDialog(it.message,false){}
                    }
                    is UiStateObject.LOADING -> {
                        showProgressDialog(true)
                    }
                    else -> Unit
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun loadData() {
        try {
            customLog("customer:$customer")
            customer?.customer?.info?.let {
                bn.content.apply {
                    txtBalance.text = "${it.balance?.amount?.toMoneyFormat()} ${it.balance?.currency}"
                    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"

                        txtCountSms.text = it?.ITEM?.value?.toMoneyFormat() ?: "0"
                        txtTypeSms.text = it?.ITEM?.unit ?: "sms"
                    }
                    bn.header.txtUserName.text = customer?.customer?.name ?: ""
                    txtTarif.text = customer?.customer?.tarifi?.name ?: getString(R.string.my_tarif)
                    txtMyNumber.text = pref.userPhone
                    toolbarMyNumber.text = pref.userPhone
                    bn.header.txtUserPhone.text = pref.userPhone
                }
            }
        } catch (e: Exception) {
//            showSnackMessage(it.message)
        }


    }

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