package uz.mobiuz.mobiservice.dev.ui.sdk.card

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.hannesdorfmann.adapterdelegates4.AdapterDelegate
import kotlinx.android.synthetic.main.mobi_uz_item_card.view.*
import timber.log.Timber
import uz.agr.sdk.core.entity.card.CardInfo
import uz.agr.sdk.coreui.extension.*
import uz.agr.sdk.coreui.model.storage.Prefs
import uz.mobiuz.mobiservice.dev.R
import uz.mobiuz.mobiservice.dev.utils.LayoutContainer

class CardDelegate(
    private val hideSettingsIcon: (Boolean),
    private val clickListener: (CardInfo, Int) -> Unit
) : AdapterDelegate<MutableList<Any>>() {

    private var amount: Long = 0L
    private var cardsList: List<String> = emptyList()

    override fun isForViewType(items: MutableList<Any>, position: Int) =
        items[position] is CardInfo

    override fun onCreateViewHolder(parent: ViewGroup): RecyclerView.ViewHolder =
        ViewHolder(parent.inflate(R.layout.mobi_uz_item_card))

    override fun onBindViewHolder(
        items: MutableList<Any>,
        position: Int,
        viewHolder: RecyclerView.ViewHolder,
        payloads: MutableList<Any>
    ) {
        amount =
            if (amount == 0L) Prefs(context = viewHolder.itemView.context).payAmount else amount
        val list = Prefs(viewHolder.itemView.context).supportedCards
        if (!list.isNullOrEmpty())
            cardsList = list.split(',')
        return (viewHolder as ViewHolder).bind(items[position] as CardInfo, position)
    }

    private inner class ViewHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView), LayoutContainer {
        private lateinit var cardInfo: CardInfo

        init {
            itemView.setOnClickListener {
                if (cardInfo.getExpiryValid()) {
                    if (cardsList.isNotEmpty()) {
                        val result = cardsList.first {
                            cardInfo.pan.startsWith(it)
                        }
                        if (result.isNotEmpty()) {
                            itemClicked()
                        }
                    } else itemClicked()
                }
            }
            if (!hideSettingsIcon) {
                containerView.btnSetting.setOnClickListener {
                    clickListener(cardInfo, adapterPosition)
                }
            }
            containerView.btnSetting.visible(!hideSettingsIcon)
        }

        @SuppressLint("SetTextI18n")
        fun bind(cardInfo: CardInfo, position: Int) {
            this.cardInfo = cardInfo

            containerView.tvCardBalance.text = cardInfo.balance.formattedMoney() + " " + containerView.context.getString(R.string.agr_mobi_uz_curr)
            containerView.tvCardPan.text = cardInfo.pan.formatToMaskedCardPan()
            containerView.tvCardExpire.text = cardInfo.getExpiryFormatted()
            containerView.tvCardHolderName.text = cardInfo.fullName
            Timber.e("PAN: ${cardInfo.pan}")
            Timber.e("EXpire: ${cardInfo.expiry}")
            val isUzCard = cardInfo.pan.startsWith("8600")
            val isHumoCard = cardInfo.pan.startsWith("9860")
            if (isHumoCard) {
                containerView.ivHumo.visible(true)
                containerView.ivUzCard.visible(false)
            } else {
                containerView.ivHumo.visible(false)
                containerView.ivUzCard.visible(true)
            }
        }

        private fun itemClicked() {
            if (amount <= cardInfo.balance)
                clickListener(cardInfo, adapterPosition)
            else showError()
        }

        private fun showError() {
            AnimationUtil().Pulse(itemView).start()
            val dialog = AlertDialog.Builder(itemView.context)
            dialog.setMessage(itemView.context.resources.getString(R.string.agr_not_emough_money))
            dialog.setPositiveButton("ok") { dialogInterface, _ ->
                dialogInterface.dismiss()
            }
            dialog.show()
        }
    }
}