package com.dreamteam.timelapse

import android.content.Context
import android.content.Intent
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.DrawableCompat
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.dreamteam.timelapse.data.ApiService
import com.dreamteam.timelapse.data.Project
import com.dreamteam.timelapse.data.ProjectRepository
import com.google.android.material.snackbar.Snackbar
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class ProjectAdapter(private val projects: MutableList<Project>, private val listener: OnEmptyStateListener) : RecyclerView.Adapter<ProjectAdapter.ProjectViewHolder>() {
    val projectRepository : ProjectRepository;
    init{
        val retrofit = Retrofit.Builder()
            .baseUrl("https://timelapse.kerboul.me/api/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        projectRepository = ProjectRepository(retrofit.create(ApiService::class.java))
        listener.onEmptyStateChanged(projects.isEmpty())
    }

    interface OnEmptyStateListener {
        fun onEmptyStateChanged(isEmpty: Boolean)
    }

    class ProjectViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val projectTitle: TextView = itemView.findViewById(R.id.projectTitle)
        val projectDescription: TextView = itemView.findViewById(R.id.projectDescription)
        val projectBadge: TextView = itemView.findViewById(R.id.projectBadge)
        val projectImage: ImageView = itemView.findViewById(R.id.projectImage)
    }

    //crée les éléments dans le fragment
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProjectViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_project_card, parent, false)

        //projects.isEmpty()

        return ProjectViewHolder(view)
    }

    // Remplit le ViewHolder avec les données
    override fun onBindViewHolder(holder: ProjectViewHolder, position: Int) {
        val project = projects[position]
        holder.projectTitle.text = project.name // Affiche le titre du projet
        holder.projectDescription.text = project.description
        holder.projectBadge.text = project.getStatusText()
        val context = holder.itemView.context
        val color = project.getStatusColor()
        Glide.with(holder.projectImage.context)
            .load("https://timelapse.kerboul.me/api/images/${project.id}/${1}") // L'URL de l'image
            .placeholder(R.drawable.not_found)
            .into(holder.projectImage)
        DrawableCompat.setTint(holder.projectBadge.background, ContextCompat.getColor(context, color))
        holder.itemView.setOnClickListener {
            val intent = Intent(context, ProjectActivity::class.java)
            intent.putExtra("PROJECT", project) // Passe les données nécessaires à l'activité cible
            context.startActivity(intent)
        }
    }
    fun removeItem(position: Int, context: Context, v : View) {
        val builder = AlertDialog.Builder(context)
        val dialog = builder.setTitle("Confirmer la supression")
            .setMessage("Voulez vous supprimer ce projet ?")
            .setPositiveButton("Supprimer") { dialog, _ ->
                if(projects[position].status != 3 && projects[position].status != 2){
                    projectRepository.deleteProject(projects[position].id, onSuccess = {
                        val name = projects[position].name
                        projects.removeAt(position)
                        notifyItemRemoved(position)
                        Snackbar.make(v.rootView, "$name supprimé avec succès !", Snackbar.LENGTH_SHORT).show()
                    }, onError = {s ->
                        dialog.dismiss()
                        notifyItemChanged(position)
                        Snackbar.make(v.rootView, "Error while trying to delete ${projects[position].name} : $s", Snackbar.LENGTH_SHORT).show()
                    })
                }else{
                    notifyItemChanged(position)
                    Snackbar.make(v.rootView, "On ne peut pas supprimer un projet dans un état intermédiaire", Snackbar.LENGTH_SHORT).show()
                }

            }
            .setNegativeButton("Annuler") { dialog, _ ->
                dialog.dismiss()
            }
            .show()
        dialog.setOnDismissListener {
            notifyItemChanged(position) // Ensure the card resets when dialog closes
        }
    }
    override fun getItemCount(): Int {
        return projects.size
    }
}