package com.divya.keyspeed.ui

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.divya.keyspeed.data.TypingHistory
import com.divya.keyspeed.databinding.ItemHistoryBinding
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

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

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

    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("MMM dd, yyyy, hh:mm a", Locale.getDefault())

        fun bind(item: TypingHistory) {
            binding.tvDate.text = dateFormat.format(Date(item.timestamp))
            binding.tvDuration.text = "${item.durationSeconds}s Test"
            binding.tvWpm.text = "${item.wpm} WPM"
            binding.tvAccuracy.text = "Accuracy: ${item.accuracy}%"
        }
    }

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

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