package com.rugvedsarika.voicereader.ui.saved

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.rugvedsarika.voicereader.databinding.ItemSavedAudioBinding
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class SavedAudioAdapter(
    private var files: List<File>,
    private var playingPath: String? = null,
    private val onPlay: (File) -> Unit,
    private val onDelete: (File) -> Unit,
    private val onDownload: (File) -> Unit,
    private val onShare: (File) -> Unit
) : RecyclerView.Adapter<SavedAudioAdapter.ViewHolder>() {

    class ViewHolder(val binding: ItemSavedAudioBinding) : RecyclerView.ViewHolder(binding.root)

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

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val file = files[position]
        holder.binding.tvFileName.text = file.name
        
        val date = Date(file.lastModified())
        val dateStr = SimpleDateFormat("MMM dd, yyyy HH:mm", Locale.getDefault()).format(date)
        holder.binding.tvFileInfo.text = holder.itemView.context.getString(com.rugvedsarika.voicereader.R.string.lbl_saved_on, dateStr)

        // Update Play/Stop icon
        val isPlaying = file.absolutePath == playingPath
        holder.binding.ivPlayPause.setImageResource(
            if (isPlaying) com.rugvedsarika.voicereader.R.drawable.ic_stop else com.rugvedsarika.voicereader.R.drawable.ic_play_arrow
        )

        holder.binding.root.setOnClickListener { onPlay(file) }
        holder.binding.btnDelete.setOnClickListener { onDelete(file) }
        holder.binding.btnDownload.setOnClickListener { onDownload(file) }
        holder.binding.btnShare.setOnClickListener { onShare(file) }
    }

    override fun getItemCount() = files.size

    fun updateFiles(newFiles: List<File>) {
        files = newFiles
        notifyDataSetChanged()
    }

    fun updatePlayingPath(path: String?) {
        playingPath = path
        notifyDataSetChanged()
    }
}
