package com.mobiuz.app.dev.ui.global

import android.os.Bundle
import android.view.View
import android.view.animation.AnimationUtils
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import co.infinum.goldfinger.Goldfinger
import com.mobiuz.app.R
import com.mobiuz.app.databinding.FragmentPinDialogBinding
import com.mobiuz.app.dev.model.PinData
import com.mobiuz.app.dev.model.SharedPref
import com.mobiuz.app.dev.ui.auth.pin.PinAdapter
import com.mobiuz.app.dev.utils.extensions.SingleBlock
import com.mobiuz.app.dev.utils.extensions.customLog
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.delay
import java.lang.Exception
import javax.inject.Inject


@AndroidEntryPoint
class FullScreenDialog : DialogFragment(R.layout.fragment_pin_dialog) {

    @Inject
    lateinit var pref: SharedPref
    private var _bn: FragmentPinDialogBinding? = null
    private val bn get() = _bn ?: throw NullPointerException("cannot inflate")
    private val data = ArrayList<PinData>()
    private val pinAdapter = PinAdapter()
    private var listener: SingleBlock<Boolean>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NO_TITLE, R.style.FullScreenDialog)
    }

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

        isCancelable = false
        setUpUI()

        loadFingerPrint()

    }

    private fun loadFingerPrint() {
        if(pref.isUseFingerPrint) {
            val golfing = Goldfinger.Builder(requireContext()).build()
            if (golfing.canAuthenticate()) {
                val params = Goldfinger.PromptParams.Builder(this)
                    .title(getString(R.string.enter_from_finger_or_face))
                    .negativeButtonText(getString(R.string.cancel))
                    .build()

                golfing.authenticate(params, object : Goldfinger.Callback {
                    override fun onResult(result: Goldfinger.Result) {
                        if(result.type() == Goldfinger.Type.SUCCESS){
                            dismiss()
                        }
                        customLog("onResult:${result.type()}, ${result.reason()}")
                    }

                    override fun onError(e: Exception) {
                        customLog("onError")
                    }
                })
            }
        }
    }

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

            rvPin.adapter = pinAdapter
            txtNotPin.isVisible = false
            pinAdapter.setOnDoneListener {
                lifecycleScope.launchWhenCreated {
                    delay(50)
                    if (pref.pin_code == it) {
                        txtNotPin.isVisible = false
                        dismiss()
                    } else {
                        cardPin.startAnimation(AnimationUtils.loadAnimation(context, R.anim.shake))
                        txtNotPin.isVisible = true
                    }
                }

            }


            for (i in 0 until btnViewGroup.childCount) {
                btnViewGroup.getChildAt(i).setOnClickListener {
                    when (it.id) {
                        R.id.btn_remove -> {
                            pinAdapter.removeItem()
                            txtNotPin.isVisible = false
                        }
                        R.id.with_password -> {
                            dismiss()
                            listener?.invoke(true)
                        }
                        R.id.btn_finger_print -> {
                            loadFingerPrint()
                        }
                        else -> {
                            val text = it as TextView
                            txtNotPin.isVisible = false
                            pinAdapter.addItem(text.text.toString().toInt())
                        }
                    }
                }
            }

        }
    }


    private fun loadData() {
        data.clear()
        for (i in 0..3) {
            data.add(PinData(-1))
        }
        pinAdapter.submitList(data)
    }

    fun setOnPinDoneListener(block: SingleBlock<Boolean>) {
        listener = block
    }

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

