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 androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.b2lmobitech.fieldcloudhrms.databinding.FragmentLeaveSummaryBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale

class LeaveSummaryFragment : Fragment() {

    private lateinit var binding: FragmentLeaveSummaryBinding
    private lateinit var adapter: LeaveSummaryAdapter
    private val leaveList = ArrayList<LeaveModel>()

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

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

        setupRecycler()
        setupMonthNavigation()
        loadLeaves()

        return binding.root
    }

    override fun onResume() {
        super.onResume()
        loadLeaves()
    }


    private fun setupRecycler() {
//        adapter = LeaveSummaryAdapter(leaveList) { leave ->
//
//            val intent = Intent(requireContext(), LeaveDetailsActivity::class.java)
//            intent.putExtra("leaveType", leave.leaveType)
//            intent.putExtra("leaveDate", leave.leaveDate)
//            intent.putExtra("days", leave.days)
//            intent.putExtra("status", leave.status)
//            intent.putExtra("reason", leave.reason)
//
//            startActivity(intent)
//        }
        adapter = LeaveSummaryAdapter(
            leaveList,
            onItemClick = { leave ->
                val intent = Intent(requireContext(), LeaveDetailsActivity::class.java)
                intent.putExtra("leaveType", leave.leaveType)
                intent.putExtra("leaveDate", leave.leaveDate)
                intent.putExtra("days", leave.days)
                intent.putExtra("status", leave.status)
                intent.putExtra("reason", leave.reason)
                startActivity(intent)
            },
            onCancelClick = { leave ->
                showCancelConfirmation(leave)
            }
        )


        binding.recyclerLeaves.layoutManager = LinearLayoutManager(requireContext())
        binding.recyclerLeaves.adapter = adapter
    }

    private fun setupMonthNavigation() {
        updateMonthLabel()

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

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

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

    private fun loadLeaves() {

        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.getLeaves(userId, orgId, month, year)
            .enqueue(object : Callback<List<LeaveModel>> {
                override fun onResponse(
                    call: Call<List<LeaveModel>>,
                    response: Response<List<LeaveModel>>
                ) {
                    Log.d("LeaveResponse", "Response: $response")

                    leaveList.clear()
                    response.body()?.let { leaveList.addAll(it) }
                    adapter.notifyDataSetChanged()

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

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

    private fun showCancelConfirmation(leave: LeaveModel) {
        androidx.appcompat.app.AlertDialog.Builder(requireContext())
            .setTitle("Cancel Leave")
            .setMessage("Are you sure you want to cancel this leave?")
            .setPositiveButton("Yes") { _, _ ->
                cancelLeave(leave)
            }
            .setNegativeButton("No", null)
            .show()
    }

    private fun cancelLeave(leave: LeaveModel) {

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

        api.cancelLeave(leave.requestId, userId)
            .enqueue(object : Callback<ApiResponse> {
                override fun onResponse(
                    call: Call<ApiResponse>,
                    response: Response<ApiResponse>
                ) {
                    if (response.isSuccessful && response.body()?.success == true) {
                        Toast.makeText(requireContext(), "Leave cancelled", Toast.LENGTH_SHORT).show()
                        loadLeaves()
                    } else {
                        Toast.makeText(requireContext(), "Unable to cancel leave", Toast.LENGTH_SHORT).show()
                    }
                }

                override fun onFailure(call: Call<ApiResponse>, t: Throwable) {
                    Toast.makeText(requireContext(), t.message, Toast.LENGTH_SHORT).show()
                }
            })
    }



}
