package uz.mobiuz.mobiservice.dev.ui.sdk.pay.success

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.activity.OnBackPressedCallback
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import com.google.gson.Gson
import dagger.hilt.android.AndroidEntryPoint
import uz.agr.sdk.core.entity.card.CardInfo
import uz.agr.sdk.coreui.extension.formattedMoney
import uz.agr.sdk.coreui.extension.showSnackMessage
import uz.agr.sdk.mobi_uz.BaseListener
import uz.agr.sdk.mobi_uz.AGRBilling
import uz.mobiuz.mobiservice.dev.R
import uz.mobiuz.mobiservice.dev.databinding.FragmentPaymentSuccessfulBinding
import uz.mobiuz.mobiservice.dev.model.Monitoring
import uz.mobiuz.mobiservice.dev.ui.base.BaseFragment
import uz.mobiuz.mobiservice.dev.ui.global.ButtonClick
import uz.mobiuz.mobiservice.dev.ui.global.CONSTANTS
import uz.mobiuz.mobiservice.dev.ui.sdk.history.HistoryViewModel
import uz.mobiuz.mobiservice.dev.utils.extensions.formatCard
import uz.mobiuz.mobiservice.dev.utils.extensions.formatPhone

/**
 * Created by DostonbekIbragimov on 06/01/2022.
 */

@AndroidEntryPoint
class PaymentSuccessfulFragment : BaseFragment(R.layout.fragment_payment_successful) {

    private var _bn: FragmentPaymentSuccessfulBinding? = null
    private val bn get() = _bn ?: throw NullPointerException("cannot inflate")

    private var saveCard: Int = 0
    private var cardNumber: String = ""
    private lateinit var monitoring: Monitoring
    private val viewModel: HistoryViewModel by viewModels()


    private val navController: NavController by lazy(LazyThreadSafetyMode.NONE) { NavHostFragment.findNavController(this) }

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

        arguments?.let {
            saveCard = it.getInt(CONSTANTS.PAY_SAVE_CARD, 0) ?: 0
            cardNumber = it.getString(CONSTANTS.PAY_CARD_NUMBER, "") ?: ""
            val arg = it.getString(CONSTANTS.PAY_MONITORING, "") ?: ""
            if (arg.isNotEmpty())
                monitoring = Gson().fromJson(arg, Monitoring::class.java)
        }
        if (::monitoring.isInitialized)
            viewModel.addMonitoring(monitoring)
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        _bn = FragmentPaymentSuccessfulBinding.bind(view)
        setUpUI()
        collects()
    }

    @SuppressLint("SetTextI18n")
    override fun setUpUI() {
        bn.apply {

            requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    navController.popBackStack(R.id.billingFragment, false)
                }
            })

            doneButton.setOnClickListener(object : ButtonClick() {
                override fun onSingleClick(v: View?) {
                    navController.popBackStack(R.id.billingFragment, false)
                }
            })
            if (::monitoring.isInitialized) {
                etAmount.text = "${monitoring.amount.formattedMoney(showDecimal = false, tiyinToSum = false)} ${
                    getString(
                        R.string
                            .agr_mobi_uz_curr
                    )
                }"
                etPhone.text = monitoring.phone.formatPhone(minus = false)
            }
            if (saveCard == CONSTANTS.IS_SAVED_CARD) {
                showSnackMessage(getString(R.string.agr_mobi_uz_card_added))
                if (cardNumber.isNotEmpty()) {
                    tvPanTitle.isVisible = true
                    etCardPan.isVisible = true
                    etCardPan.text = cardNumber.formatCard()
                }
            }
            if (saveCard == CONSTANTS.IS_NOT_SAVED_CARD) {
                if (cardNumber.length == 20)
                    deleteCard(cardNumber.substring(0, 16), cardNumber.substring(16, 20))
                showSnackMessage(getString(R.string.agr_mobi_uz_card_not_save))
            }

        }
    }

    private fun deleteCard(cardNumber: String, cardExpiry: String) {
        AGRBilling.getLocalCards(object : BaseListener<List<CardInfo>> {
            override fun error(message: String) {}
            override fun loading(boolean: Boolean) {}
            override fun success(data: List<CardInfo>) {
                val card: CardInfo? = data.find {
                    it.expiry.substring(0, 2) == cardExpiry.substring(2, 4) &&
                            it.expiry.substring(2, 4) == cardExpiry.substring(0, 2)
                            && it.pan.replace(" ", "").substring(0, 6) == cardNumber.replace(" ", "").substring(0, 6)
                            && it.pan.replace(" ", "").substring(it.pan.length - 4, it.pan.length) ==
                            cardNumber.replace(" ", "").substring(cardNumber.length - 4, cardNumber.length)
                }
                if (card != null) {
                    AGRBilling.deleteCard(card, object : BaseListener<Boolean> {
                        override fun error(message: String) {}
                        override fun loading(boolean: Boolean) {}
                        override fun success(data: Boolean) {}
                    })
                }
            }
        })
    }


    override fun collects() {

    }

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