package com.dreamteam.timelapse

import android.graphics.Canvas
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.util.Log
import android.util.TypedValue
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.GridLayout
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.dreamteam.timelapse.data.ProjectRepository
import com.dreamteam.timelapse.databinding.FragmentProjetsBinding
import com.dreamteam.timelapse.data.ApiService
import com.dreamteam.timelapse.data.Project
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

/**
 * A simple [Fragment] subclass as the default destination in the navigation.
 */

class ProjetsFrag : Fragment(), ProjectAdapter.OnEmptyStateListener {

    private lateinit var projectRepository: ProjectRepository
    //private lateinit var listView: ListView
    private lateinit var recyclerView: RecyclerView
    private lateinit var projectAdapter: ProjectAdapter
    private var _binding: FragmentProjetsBinding? = null
    private val binding get() = _binding!!

    private lateinit var apiService: ApiService // Déclare l'apiService
    private var projects: List<Project> = emptyList() // Déclare une liste de projets vide
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Initialiser apiService ici, par exemple, en utilisant Retrofit
        val retrofit = Retrofit.Builder()
            .baseUrl("https://timelapse.kerboul.me/api/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        apiService = retrofit.create(ApiService::class.java) // Crée une instance d'ApiService
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentProjetsBinding.inflate(inflater, container, false)
        Log.d("ProjetsFrag", "Fragment Projets créé")

        projectRepository = ProjectRepository(apiService)  // Tu initialises ton repository
        //fetchProjects()

        return _binding?.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val swipeRefreshLayout = binding.swipeRefreshLayout

        swipeRefreshLayout.setOnRefreshListener {
            fetchProjects()
            Log.d("ProjetsFrag", "Actualisation des projets")
        }
        fetchProjects()

        recyclerView = binding.recyclerView // view.findViewById(R.id.recyclerView)
        recyclerView.layoutManager =  LinearLayoutManager(context)

        val itemTouchHelper = ItemTouchHelper(object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT) {
            private val background = ColorDrawable(Color.RED) // Red background
            private val deleteIcon = context?.let { ContextCompat.getDrawable(it, R.drawable.ic_delete) }
            override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
                return false
            }

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                val position = viewHolder.adapterPosition
                context?.let { (recyclerView.adapter as ProjectAdapter).removeItem(position, it, viewHolder.itemView) }
            }
            override fun onChildDraw(
                c: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder,
                dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean
            ) {
                val itemView = viewHolder.itemView
                val backgroundCornerOffset = 20 // Slight offset for smooth animation

                background.setBounds(
                    itemView.left,
                    itemView.top,
                    itemView.left + dX.toInt() - backgroundCornerOffset,
                    itemView.bottom
                )
                //background.draw(c)

                // Position the delete icon
                val iconMargin = (itemView.height - deleteIcon!!.intrinsicHeight) / 2
                val iconRight = itemView.left + iconMargin + deleteIcon.intrinsicWidth
                val iconLeft = itemView.left + iconMargin
                val iconTop = itemView.top + (itemView.height - deleteIcon.intrinsicHeight) / 2
                val iconBottom = iconTop + deleteIcon.intrinsicHeight

                deleteIcon.setBounds(iconLeft, iconTop, iconRight, iconBottom)
                deleteIcon.draw(c)


                super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
            }
        })

        itemTouchHelper.attachToRecyclerView(recyclerView)
    }

    private fun fetchProjects() {
        // Simulez l'appel API
        binding.swipeRefreshLayout.setEnabled(true)
        binding.swipeRefreshLayout.setRefreshing(true)
        //binding.swipeRefreshLayout.

        //binding.swipeRefreshLayout.dragDown()
        Log.d("ProjetsFrag", "User has refreshed the projects list")
        projectRepository.fetchProjects(
            onSuccess = { projects ->
                Log.d("ProjetsFrag", "Projets reçus : $projects")
                this.projects = projects
                this.projectAdapter = ProjectAdapter(this.projects.toMutableList(), this) //TODO : Potentiel problème pour les refresh ici (update de l'adapter ou un truc du genre à voir)
                this.recyclerView.adapter = this.projectAdapter
                // Mettre à jour le RecyclerView ou autre traitement
            },
            onError = { errorMessage ->
                Log.e("ProjetsFrag prout", errorMessage)
                //onEmptyStateChanged(true)
                this.projects = listOf<Project>()
                this.projectAdapter = ProjectAdapter(this.projects.toMutableList(), this) //TODO : Potentiel problème pour les refresh ici (update de l'adapter ou un truc du genre à voir)
                this.recyclerView.adapter = this.projectAdapter

            }
        )
        binding.swipeRefreshLayout.isRefreshing = false
    }
    override fun onEmptyStateChanged(isEmpty: Boolean) {
        // Afficher ou masquer le message
        if (isEmpty) {
            binding.noProjectsText.visibility = View.VISIBLE
        } else {
            binding.noProjectsText.visibility = View.GONE
        }
    }

//    override fun onDestroyView() {
//        super.onDestroyView()
//        _binding = null
//    }
}