package com.rugvedsarika.easymath.ui.progress

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.rugvedsarika.easymath.data.db.MathHistoryEntity
import com.rugvedsarika.easymath.databinding.ItemHistoryBinding
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class HistoryAdapter : ListAdapter<MathHistoryEntity, HistoryAdapter.HistoryViewHolder>(DiffCallback) {

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

    override fun onBindViewHolder(holder: HistoryViewHolder, position: Int) {
        val item = getItem(position)
        holder.bind(item)
    }

    class HistoryViewHolder(private val binding: ItemHistoryBinding) : RecyclerView.ViewHolder(binding.root) {
        private val dateFormat = SimpleDateFormat("dd MMM yyyy HH:mm", Locale.getDefault())

        fun bind(item: MathHistoryEntity) {
            binding.textCategory.text = "${item.category} (${item.level})"
            binding.textDate.text = dateFormat.format(Date(item.timestamp))
            binding.textScore.text = "${item.score}/${item.totalQuestions}"
            binding.textAccuracy.text = "%.0f%%".format(item.accuracy)
        }
    }

    companion object DiffCallback : DiffUtil.ItemCallback<MathHistoryEntity>() {
        override fun areItemsTheSame(oldItem: MathHistoryEntity, newItem: MathHistoryEntity): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: MathHistoryEntity, newItem: MathHistoryEntity): Boolean {
            return oldItem == newItem
        }
    }
}
