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

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.util.TypedValue
import androidx.cardview.widget.CardView
import androidx.core.view.isVisible
import kotlinx.android.synthetic.main.view_select_card.view.*
import uz.agr.sdk.core.entity.card.CardInfo
import uz.agr.sdk.coreui.extension.drawable
import uz.agr.sdk.coreui.extension.formatToMaskedCardPan
import uz.agr.sdk.coreui.extension.formattedMoney
import uz.mobiuz.mobiservice.dev.R
import uz.mobiuz.mobiservice.dev.utils.extensions.tint

class SelectCardView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : CardView(context, attrs, defStyleAttr) {

    private var stateViewNewCard = false

    init {
        inflate(context, R.layout.view_select_card, this)
        cardElevation = 0F
        radius = resources.getDimension(R.dimen.select_card_view_corner_radius)
        val outValue = TypedValue()
        context.theme.resolveAttribute(android.R.attr.selectableItemBackground, outValue, true)
        foreground = context.drawable(outValue.resourceId)
    }

    fun init(onClickListener: () -> Unit) {
        setOnClickListener { onClickListener.invoke() }
    }

    @SuppressLint("SetTextI18n")
    fun showCard(cardInfo: CardInfo, position: Int) {
        stateViewNewCard = false
        cardContent.setBackgroundResource(getCardBackground(position % 3))
        tvCardPan.isVisible = true
        tvCardBalance.isVisible = true
        tvNewCard.isVisible = false
        arrow.tint(R.color.agr_white)

        tvCardPan.text = cardInfo.pan.formatToMaskedCardPan()
        tvCardBalance.text = cardInfo.balance.formattedMoney() + " " + context.getString(R.string.agr_mobi_uz_curr)
    }

    fun showProgress(show: Boolean) {
        if (stateViewNewCard.not()) {
            progressView.isVisible = show
        }
    }

    fun showNewCard() {
        stateViewNewCard = true
        cardContent.setBackgroundResource(R.drawable.add_card_bg)
        tvCardPan.isVisible = false
        tvCardBalance.isVisible = false
        progressView.isVisible = false
        tvNewCard.isVisible = true
        arrow.tint(R.color.primary100)
    }

    private fun getCardBackground(position: Int): Int {
        return when (position) {
            0 -> R.drawable.select_card
            1 -> R.drawable.select_card
            2 -> R.drawable.select_card
            else -> R.drawable.select_card
        }
    }
}
