package uz.ssd.mobiuz.ui.auth

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.core.hardware.fingerprint.FingerprintManagerCompat
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import androidx.recyclerview.widget.LinearLayoutManager
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.delay
import uz.ssd.mobiuz.MainActivity
import uz.ssd.mobiuz.R
import uz.ssd.mobiuz.databinding.FragmentPinBinding
import uz.ssd.mobiuz.model.PinData
import uz.ssd.mobiuz.model.SharedPref
import uz.ssd.mobiuz.ui.base.BaseFragment
import uz.ssd.mobiuz.utils.Utils
import uz.ssd.mobiuz.utils.extensions.showMessage
import javax.inject.Inject

@AndroidEntryPoint
class ConfirmPinFragment : BaseFragment(R.layout.fragment_pin) {

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

    private val viewModel: AuthViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            pinCode =  it.getString("pinCode","") ?: ""
        }
    }


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

        setUpUI()
        collects()

    }

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

            rvPin.adapter = pinAdapter
            txtEnterPin.text = getString(R.string.confirm_pin)
            txtNotPin.isVisible = false
            pinAdapter.setOnDoneListener {
                lifecycleScope.launchWhenCreated {
                    delay(500)
                        if (pinCode == it) {
                            pref.pin_code = pinCode
                            txtNotPin.isVisible = false
                            navigate()
                        } else {
                            txtNotPin.isVisible = true
                        }
                }

            }

            toolbar.setNavigationOnClickListener {
                navController.navigateUp()
            }
            for (i in 0 until btnViewGroup.childCount) {
                btnViewGroup.getChildAt(i).setOnClickListener {
                    if (it.id == R.id.btn_remove) {
                        pinAdapter.removeItem()
                        txtNotPin.isVisible = false
                    } else {
                        val text = it as TextView
                        pinAdapter.addItem(text.text.toString().toInt())
                    }
                }
            }

        }
    }

    private fun navigate() {
        val manager = FingerprintManagerCompat.from(requireContext())
        val isEnabled = manager.isHardwareDetected && manager.hasEnrolledFingerprints()

        if(isEnabled){
            navController.navigate(R.id.biometricFragment, null, Utils.navOptions())
        }else{
            startActivity(Intent(requireContext(),MainActivity::class.java))
            requireActivity().finish()
        }
    }

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