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.config.Config
import com.sambath.kunkhmer.remote.News
import com.sambath.kunkhmer.remote.NewsData
import com.squareup.picasso.Picasso
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.TimeZone

class TopNewsAdapter(var cardList: MutableList<News>, private val itemClickListener: OnItemClickListener) : RecyclerView.Adapter<TopNewsAdapter.ViewHolder>() {
    interface OnItemClickListener {
        fun onItemClick(newsItem: News)
    }

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

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val currentItem = cardList[position]
        if (!currentItem.filename.isNullOrEmpty()) {
            Picasso.get()
                .load(Config.BASE_URL + "/v1/new/image/" + currentItem.filename)
                .into(holder.imageView);
        } else {
            Picasso.get()
                .load(R.drawable.ic_logo_header)
                .into(holder.imageView);
        }
        holder.dateTextView.text = parseAndFormatDate(currentItem.createdAt)
        holder.titleTextView.text = currentItem.title
        holder.subTextView.text = currentItem.desc

        holder.itemView.setOnClickListener{
            itemClickListener.onItemClick(cardList[position])
        }
    }

    override fun getItemCount() = cardList.size

    // Holds the views for adding it to image and text
    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)
        val subTextView: TextView = itemView.findViewById(R.id.descTextView)
    }

    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)
    }
}