package com.b2lmobitech.fieldcloudhrms

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView

class PayslipAdapter(
    private val list: List<PayslipModel>
) : RecyclerView.Adapter<PayslipAdapter.ViewHolder>() {

    inner class ViewHolder(v: View) : RecyclerView.ViewHolder(v) {
        val tvEmpName: TextView = v.findViewById(R.id.tvEmpName)
        val tvEmpInfo: TextView = v.findViewById(R.id.tvEmpInfo)
        val layoutEarnings: LinearLayout = v.findViewById(R.id.layoutEarnings)
        val layoutDeductions: LinearLayout = v.findViewById(R.id.layoutDeductions)
        val tvNetPay: TextView = v.findViewById(R.id.tvNetPay)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_payslip, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(h: ViewHolder, pos: Int) {
        val p = list[pos]

        // Employee info
        h.tvEmpName.text = p.employeeName
        h.tvEmpInfo.text =
            "Emp ID: ${p.employeeId} \nDesignation: ${p.designation} \nDepartment: ${p.department}\nPAN: ${p.panNumber}"

        // Clear layouts (important!)
        h.layoutEarnings.removeAllViews()
        h.layoutDeductions.removeAllViews()

        // Earnings
        addRow(h.layoutEarnings, "Basic Salary", p.basicSalary)
        addRow(h.layoutEarnings, "HRA", p.hra)
        addRow(h.layoutEarnings, "Dearness Allowance", p.dearnessAllowance)
        addRow(h.layoutEarnings, "LTA", p.lta)
        addRow(h.layoutEarnings, "Bonus", p.bonus)
        addRow(h.layoutEarnings, "Transport Allowance", p.transportAllowance)
        addRow(h.layoutEarnings, "Medical Allowance", p.medicalAllowance)
        addRow(h.layoutEarnings, "Other Allowance", p.otherAllowance)

        // Deductions
        addRow(h.layoutDeductions, "PF", p.pf)
        addRow(h.layoutDeductions, "TDS", p.tds)
        addRow(h.layoutDeductions, "Arrears", p.arrears)
        addRow(h.layoutDeductions, "Other Deduction", p.otherDeduction)

        // Net Pay
        h.tvNetPay.text = "Net Pay : ₹${String.format("%,.2f", p.netSalary)}"
    }

    override fun getItemCount() = list.size

    private fun addRow(parent: LinearLayout, label: String, amount: Double) {
        if (amount <= 0) return

        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.row_amount, parent, false)

        view.findViewById<TextView>(R.id.tvLabel).text = label
        view.findViewById<TextView>(R.id.tvAmount).text =
            "₹${String.format("%,.2f", amount)}"

        parent.addView(view)
    }
}
