package com.b2lmobitech.fieldcloudhrms

import android.content.Context
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.FragmentPayslipBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.text.SimpleDateFormat
import java.util.*

class PayslipFragment : Fragment() {

    private lateinit var binding: FragmentPayslipBinding
    private lateinit var adapter: PayslipAdapter
    private val payslipList = ArrayList<PayslipModel>()

    private val calendar = Calendar.getInstance()
    private var joinDate: Date? = null

    private val api by lazy { RetrofitClient.instance }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        binding = FragmentPayslipBinding.inflate(inflater, container, false)

        setupRecycler()
        setupMonthNavigation()
        fetchEmployeeDetails()

        return binding.root
    }

    // ---------------- Recycler ----------------
    private fun setupRecycler() {
        adapter = PayslipAdapter(payslipList)
        binding.recyclerPayslip.layoutManager = LinearLayoutManager(requireContext())
        binding.recyclerPayslip.adapter = adapter
    }

    // ---------------- Month Navigation ----------------
    private fun setupMonthNavigation() {
        updateMonthLabel()

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

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

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

    // ---------------- Fetch Employee (join_date) ----------------
    private fun fetchEmployeeDetails() {

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

        api.getEmployeeProfile(userId, orgId)
            .enqueue(object : Callback<EmployeeModel> {
                override fun onResponse(
                    call: Call<EmployeeModel>,
                    response: Response<EmployeeModel>
                ) {
                    val employee = response.body()

                    if (employee == null) {
                        showNoData("Employee data not found")
                        return
                    }

                    val joinDateStr = employee.join_date
                    Log.d("joindate","$joinDateStr")

                    val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())

                    joinDate = if (!joinDateStr.isNullOrEmpty()
                        && joinDateStr != "0000-00-00"
                    ) {
                        sdf.parse(joinDateStr)
                    } else {
                        null
                    }

                    loadPayslip()
                }

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

    // ---------------- Load Payslip ----------------
    private fun loadPayslip() {

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

        //  Join date missing
        if (joinDate == null) {
            showNoData("Employee join date not available")
            return
        }

        // Normalize join month
        val joinCal = Calendar.getInstance()
        joinCal.time = joinDate!!
        joinCal.set(Calendar.DAY_OF_MONTH, 1)

        // Normalize selected month
        val selectedCal = calendar.clone() as Calendar
        selectedCal.set(Calendar.DAY_OF_MONTH, 1)

        //  Before joining month
        if (selectedCal.before(joinCal)) {
            showNoData("Employee not joined yet")
            return
        }

        //  Future month
        // Normalize current month
        val currentCal = Calendar.getInstance()
        currentCal.set(Calendar.DAY_OF_MONTH, 1)
        currentCal.set(Calendar.HOUR_OF_DAY, 0)
        currentCal.set(Calendar.MINUTE, 0)
        currentCal.set(Calendar.SECOND, 0)
        currentCal.set(Calendar.MILLISECOND, 0)

        // Normalize selected month
        selectedCal.set(Calendar.HOUR_OF_DAY, 0)
        selectedCal.set(Calendar.MINUTE, 0)
        selectedCal.set(Calendar.SECOND, 0)
        selectedCal.set(Calendar.MILLISECOND, 0)

        //  Only block STRICT future months
        if (!selectedCal.before(currentCal)) {
            showNoData("Payslip not generated yet")
            return
        }

        //  Valid month → API call
        val month = calendar.get(Calendar.MONTH) + 1
        val year = calendar.get(Calendar.YEAR)

        api.getPayslip(userId, orgId, month, year)
            .enqueue(object : Callback<PayslipModel> {
                override fun onResponse(
                    call: Call<PayslipModel>,
                    response: Response<PayslipModel>
                ) {

                    payslipList.clear()

                    response.body()?.let {
                        payslipList.add(it)
                    }

                    response.body()?.basicSalary?.let {
                        if (it<=0)
                            showNoData("No Salary details available")
                            adapter.notifyDataSetChanged()
                    }
                    binding.txtNoData.visibility =
                        if (payslipList.isEmpty()) View.VISIBLE else View.GONE
                }

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

    // ---------------- Helper ----------------
    private fun showNoData(message: String) {
        payslipList.clear()
        adapter.notifyDataSetChanged()
        binding.txtNoData.text = message
        binding.txtNoData.visibility = View.VISIBLE
    }
}
