package com.seatel.mobilehall.ui.yes_member.adapter

import android.content.Context
import android.os.Build
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.RecyclerView
import com.seatel.mobilehall.databinding.ItemEarnCoinHistoryBinding
import com.seatel.mobilehall.ui.yes_member.model.EarnCoinHistoryData
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.util.Locale

class EarnCoinHistoryAdapter(
    private val mContext: Context,
    private val earnCoinHistoryModel: ArrayList<EarnCoinHistoryData>
) : RecyclerView.Adapter<EarnCoinHistoryAdapter.ViewHolder>() {

    @RequiresApi(Build.VERSION_CODES.O)
    private fun formatDateCoin(input: String): String {
        return try {
            val inputFormatter = DateTimeFormatter.ISO_DATE_TIME
            val outputFormatter = DateTimeFormatter.ofPattern("dd MMM yyyy", Locale.ENGLISH)
            val dateTime = ZonedDateTime.parse(input, inputFormatter).toLocalDate()
            dateTime.format(outputFormatter)
        } catch (e: Exception) {
            input // Return original input if parsing fails
        }
    }

    inner class ViewHolder(private val binding: ItemEarnCoinHistoryBinding) :
        RecyclerView.ViewHolder(binding.root) {

        @RequiresApi(Build.VERSION_CODES.O)
        fun bind(data: EarnCoinHistoryData) {
            binding.tvPlanName.text = data.pricePlan
            binding.tvDate.text = formatDateCoin(data.earnDate)
            binding.tvExpiry.text = formatDateCoin(data.expiredDate)
            binding.tvEarnCoin.text = "+${data.coin}"
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = ItemEarnCoinHistoryBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ViewHolder(binding)
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(earnCoinHistoryModel[position])
    }

    override fun getItemCount(): Int = earnCoinHistoryModel.size
}
