package com.mobiuz.app.dev.ui.settings.safety.pin

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.view.animation.AnimationUtils
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.mobiuz.app.R
import com.mobiuz.app.databinding.FragmentOldPinBinding
import com.mobiuz.app.dev.model.PinData
import com.mobiuz.app.dev.model.SharedPref
import com.mobiuz.app.dev.ui.auth.AuthActivity
import com.mobiuz.app.dev.ui.auth.pin.PinAdapter
import com.mobiuz.app.dev.ui.base.BaseFragment
import com.mobiuz.app.dev.ui.global.CONSTANTS
import com.mobiuz.app.dev.utils.Utils
import com.mobiuz.app.dev.utils.extensions.getColorCompat
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.delay
import javax.inject.Inject

@AndroidEntryPoint
class OldPinFragment : BaseFragment(R.layout.fragment_old_pin) {

    @Inject
    lateinit var pref: SharedPref
    private var _bn: FragmentOldPinBinding? = null
    private val bn get() = _bn ?: throw NullPointerException("cannot inflate")
    private val navController: NavController by lazy(LazyThreadSafetyMode.NONE) { NavHostFragment.findNavController(this) }
    private val data = ArrayList<PinData>()
    private val pinAdapter = PinAdapter()
    private var count = 3
    private lateinit var decorView: View


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

        count = 3
        setUpUI()
        collects()

    }

    override fun setUpUI() {
        bn.apply {
            loadData()
            toolbar.setNavigationOnClickListener {
                navController.navigateUp()
            }
            rvPin.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
            rvPin.setHasFixedSize(true)

            rvPin.adapter = pinAdapter

            pinAdapter.setOnDoneListener {
                lifecycleScope.launchWhenCreated {
                    delay(50)
                    if (pref.pinCode == it) {
                        navController.navigate(R.id.newPinFragment, null, Utils.navOptions())
                    } else {
                        cardPin.startAnimation(AnimationUtils.loadAnimation(requireContext(), R.anim.shake))
                        count--
                        if(count == 0){
                            lifecycleScope.launchWhenCreated {
                                loadError(true)
                                delay(1000)
                                pref.clearUserData()
                                val intent = Intent(requireContext(), AuthActivity::class.java)
                                intent.putExtra(CONSTANTS.TYPE_AUTH, CONSTANTS.LOGIN)
                                intent.putExtra(CONSTANTS.PHONE, pref.userPhone)
                                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_TASK_ON_HOME
                                startActivity(intent)
                                requireActivity().finish()
                            }
                        }else{
                            loadError(true)
                        }

                    }
                }
            }

            toolbar.setNavigationOnClickListener {
                navController.navigateUp()
            }
            for (i in 0 until btnViewGroup.childCount) {
                btnViewGroup.getChildAt(i).setOnClickListener {
                    when (it.id) {
                        R.id.btn_remove -> {
                            loadError(false)
                            pinAdapter.removeItem()
                        }
                        R.id.btn_forget_pin -> {

                        }
                        else -> {
                            loadError(false)
                            val text = it as TextView
                            pinAdapter.addItem(text.text.toString().toInt())
                        }
                    }
                }
            }

        }
    }

    private fun loadError(status:Boolean){
        bn.apply {
            if (count == 0){
                errorTitle.text = getString(R.string.impossible_change_pin)
                errorText.text = getString(R.string.popitok_error)
            }else{
                errorText.text = getString(R.string.popitok,count.toString())
            }
            errorLayout.isVisible = status
            div.setBackgroundColor(if(status) getColorCompat(R.color.primary100) else Color.TRANSPARENT)
            decorView = requireActivity().window.decorView
            decorView.systemUiVisibility = if(status) View.VISIBLE else{decorView.systemUiVisibility or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR}
        }
    }
    private fun loadData() {
        data.clear()
        for (i in 0..3) {
            data.add(PinData(-1))
        }
        pinAdapter.submitList(data)
    }

    override fun collects() {

    }

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