package com.dreamteam.timelapse

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.dreamteam.timelapse.data.VideoRepository
import com.dreamteam.timelapse.data.ApiService
import com.dreamteam.timelapse.data.Video
import com.dreamteam.timelapse.databinding.FragmentVideosBinding
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

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

class VideoFrag : Fragment(), VideoAdapter.OnEmptyStateListener {

    private lateinit var videoRepository: VideoRepository
    //private lateinit var listView: ListView
    private lateinit var recyclerView: RecyclerView
    private lateinit var videoAdapter: VideoAdapter
    private var _binding: FragmentVideosBinding? = null
    private val binding get() = _binding!!

    private lateinit var apiService: ApiService // Déclare l'apiService
    private var videos: List<Video> = 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 = FragmentVideosBinding.inflate(inflater, container, false)
        Log.d("ProjetsFrag", "Fragment Projets créé")

        videoRepository = VideoRepository(apiService)  // Tu initialises ton repository
        //fetchVideos()

        return _binding?.root
    }

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

        val swipeRefreshLayout = binding.swipeRefreshLayout

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

        recyclerView = binding.recyclerView // view.findViewById(R.id.recyclerView)
        recyclerView.layoutManager = GridLayoutManager(context, 2, RecyclerView.VERTICAL, false)//LinearLayoutManager(context)
        recyclerView.addItemDecoration(ProjectActivity.GridSpacingItemDecoration(50)) // 16px spacing


    }

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

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

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

}