package com.b2lmobitech.fieldcloudhrms

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import java.util.Calendar
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.b2lmobitech.fieldcloudhrms.databinding.FragmentTimesheetBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.text.SimpleDateFormat
import java.util.Locale

class TimesheetFragment : Fragment() {

    private lateinit var binding: FragmentTimesheetBinding
    private val timesheetList = ArrayList<TimesheetModel>()
    private lateinit var adapter: TimesheetAdapter

    private var calendar = Calendar.getInstance()
    private val api by lazy { RetrofitClient.instance }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentTimesheetBinding.inflate(inflater, container, false)

        setupRecycler()
        setupMonthNavigation()
        setupFab()

        loadTimesheets()

        return binding.root
    }

    private fun setupRecycler() {
        adapter = TimesheetAdapter(timesheetList)
        binding.rvTimesheets.layoutManager = LinearLayoutManager(requireContext())
        binding.rvTimesheets.adapter = adapter
    }

    private fun setupMonthNavigation() {
        updateMonthLabel()

        binding.btnPrevMonth.setOnClickListener {
            calendar.add(Calendar.MONTH, -1)
            updateMonthLabel()
            loadTimesheets()
        }

        binding.btnNextMonth.setOnClickListener {
            calendar.add(Calendar.MONTH, 1)
            updateMonthLabel()
            loadTimesheets()
        }
    }

    private fun updateMonthLabel() {
        val format = SimpleDateFormat("MMM yyyy", Locale.getDefault())
        binding.txtMonth.text = format.format(calendar.time)
    }

    private fun setupFab() {
        binding.fabAdd.setOnClickListener {
            val intent = Intent(requireContext(), SubmitTimesheetFragment::class.java)
            startActivity(intent)
        }
    }

    private fun loadTimesheets() {

        val sharedPref = requireContext().getSharedPreferences("login_pref", Context.MODE_PRIVATE)
        val userId = sharedPref.getString("user_id", "") ?: ""
        val orgId = sharedPref.getString("org_id", "") ?: ""

        val month = calendar.get(Calendar.MONTH) + 1
        val year = calendar.get(Calendar.YEAR)

        api.getTimesheets(userId, orgId, month, year)
            .enqueue(object : Callback<List<TimesheetModel>> {
                override fun onResponse(
                    call: Call<List<TimesheetModel>>,
                    response: Response<List<TimesheetModel>>
                ) {
                    Log.d("response","$response")
                    timesheetList.clear()
                    response.body()?.let { timesheetList.addAll(it) }
                    adapter.notifyDataSetChanged()

                    binding.txtNoData.visibility =
                        if (timesheetList.isEmpty()) View.VISIBLE else View.GONE
                }

                override fun onFailure(call: Call<List<TimesheetModel>>, t: Throwable) {
                    Toast.makeText(requireContext(), "Failed: ${t.message}", Toast.LENGTH_SHORT).show()
                }
            })
    }
}
