package com.sambath.kunkhmer.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.sambath.kunkhmer.R
import com.sambath.kunkhmer.remote.Highlight
import com.squareup.picasso.Picasso
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.TimeZone

class HighlightNewsAdapter (var cardList: MutableList<Highlight>, private val listener: OnItemClickListener) : RecyclerView.Adapter<HighlightNewsAdapter.ViewHolder>() {

    interface OnItemClickListener {
        fun onItemClick(position: Int)
    }

    class CardViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val itemView = LayoutInflater.from(parent.context)
            .inflate(R.layout.layout_highlight_item_card, parent, false)
        return ViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val currentItem = cardList[position]
        val videoId = currentItem.url.substringAfterLast("/")
        val thumbnailUrl = "https://img.youtube.com/vi/$videoId/0.jpg"

        Picasso.get()
            .load(thumbnailUrl)
            .placeholder(R.drawable.ic_logo_header)
            .into(holder.imageView);

        holder.dateTextView.text = parseAndFormatDate(currentItem.date)
        holder.titleTextView.text = currentItem.title
    }

    override fun getItemCount() = cardList.size

    // Holds the views for adding it to image and text
    inner class ViewHolder(ItemView: View) : RecyclerView.ViewHolder(ItemView) {
        val imageView: ImageView = itemView.findViewById(R.id.imageView)
        val dateTextView: TextView = itemView.findViewById(R.id.dateTextView)
        val titleTextView: TextView = itemView.findViewById(R.id.titleTextView)

        init {
            itemView.setOnClickListener {
                val position = adapterPosition
                if (position != RecyclerView.NO_POSITION) {
                    listener.onItemClick(position)
                }
            }
        }
    }

    private fun parseAndFormatDate(dateString: String): String {
        // Create a SimpleDateFormat for parsing the date string
        val parser = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault())
        parser.timeZone = TimeZone.getTimeZone("UTC")

        // Parse the date
        val date = parser.parse(dateString)

        // Create a SimpleDateFormat for formatting the date
        val formatter = SimpleDateFormat("dd MMM yyyy HH:mm", Locale.getDefault())
        formatter.timeZone = TimeZone.getDefault() // Use local timezone

        // Format the date
        return formatter.format(date)
    }
}