package com.seatel.mobilehall.ui.home.viewholder

import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.seatel.mobilehall.R
import com.seatel.mobilehall.databinding.HolderCartScratchItemBinding
import com.seatel.mobilehall.ui.home.activity.OrderActivity
import com.seatel.mobilehall.ui.home.model.CartModel
import com.seatel.mobilehall.util.SeatelUtils
import com.seatel.mobilehall.util.manager.OrderingManager
import java.util.*

class CartScratchViewHolder(private val binding: HolderCartScratchItemBinding) :
    RecyclerView.ViewHolder(binding.root) {

    fun onBind(data: CartModel) {
        // Binding data to views using ViewBinding
        binding.tvScratchPrice.text = String.format(Locale.US, "$%.2f", data.unitPrice)
        binding.tvTotal.text = String.format(Locale.US, "%.2f", data.quantity * data.unitPrice)
        binding.tvScratchAmount.text = String.format(Locale.US, "$%.2f", data.scratchCardAmount)
        binding.tvScratchQty.text = String.format(Locale.US, "%d", data.quantity)
        binding.checkBox.isChecked = data.isSelected

        if (TextUtils.isEmpty(data.scratchCardIcon)) {
            binding.scratchImage.setImageResource(R.drawable.ic_scratch_card)
        } else {
            Glide.with(binding.root.context).load(data.scratchCardIcon).into(binding.scratchImage)
        }

        if (binding.root.context is OrderActivity) {
            binding.layoutTotal.visibility = View.GONE
            binding.checkBox.visibility = View.GONE
            binding.imageViewRemove.visibility = View.GONE
            binding.imageViewAdd.visibility = View.GONE
            binding.tvScratchQty.background = null
            binding.tvScratchQty.setPadding(0, 0, 0, 0)
        } else {
            val param = FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            param.topMargin = SeatelUtils.convertDpToPx(binding.root.context, 10)
            binding.root.layoutParams = param
        }

        // Setting up click listeners
        binding.imageViewRemove.setOnClickListener {
            OrderingManager.getInstance().updateCartItem(binding.root.context, data, data.quantity - 1)
        }

        binding.imageViewAdd.setOnClickListener {
            OrderingManager.getInstance().updateCartItem(binding.root.context, data, data.quantity + 1)
        }
    }
}
