package com.b2lmobitech.fieldcloudhrms

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.floatingactionbutton.FloatingActionButton
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class TravelFragment : Fragment(R.layout.fragment_travel) {

    private lateinit var recyclerView: RecyclerView
    private lateinit var adapter: TravelAdapter
    private val travelList = ArrayList<TravelModel>()

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

        recyclerView = view.findViewById(R.id.rvTravel)
        recyclerView.layoutManager = LinearLayoutManager(requireContext())
        adapter = TravelAdapter(travelList)
        recyclerView.adapter = adapter

//        loadTravelFromServer()
        val sharedPref =
            requireContext().getSharedPreferences("login_pref", Context.MODE_PRIVATE)

        val userId = sharedPref.getString("user_id", "") ?: ""
        val orgId = sharedPref.getString("org_id", "") ?: ""

        if (userId.isNotEmpty() && orgId.isNotEmpty()) {
            loadTravelFromServer(userId, orgId)
        }

        view.findViewById<FloatingActionButton>(R.id.fabAdd).setOnClickListener {
            // Open Create Travel screen
            startActivity(Intent(requireContext(), AddTravelActivity::class.java))
        }
    }

    private fun loadTravelFromServer(userId: String, orgId: String) {
        // Example (replace with Retrofit / Volley)
        RetrofitClient.instance.getTravelList(userId, orgId)
            .enqueue(object : Callback<TravelResponse> {

                override fun onResponse(
                    call: Call<TravelResponse>,
                    response: Response<TravelResponse>
                ) {
                    if (response.isSuccessful && response.body()?.success == true) {

                        travelList.clear()
                        travelList.addAll(response.body()!!.data)
                        adapter.notifyDataSetChanged()
                    }
                }

                override fun onFailure(call: Call<TravelResponse>, t: Throwable) {
                    Log.e("TravelFragment", "API Error", t)
                }
            })
    }
}
