package com.b2lmobitech.fieldcloudhrms

import android.os.Build
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.RecyclerView
import com.b2lmobitech.fieldcloudhrms.databinding.ItemLeaveSummaryBinding
import java.time.LocalDate

class LeaveSummaryAdapter(
    private val list: List<LeaveModel>,
    private val onItemClick: (LeaveModel) -> Unit,
    private val onCancelClick: (LeaveModel) -> Unit
) : RecyclerView.Adapter<LeaveSummaryAdapter.LeaveVH>() {

    class LeaveVH(val binding: ItemLeaveSummaryBinding) :
        RecyclerView.ViewHolder(binding.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LeaveVH {
        val binding = ItemLeaveSummaryBinding.inflate(
            LayoutInflater.from(parent.context), parent, false
        )
        return LeaveVH(binding)
    }

    override fun getItemCount(): Int = list.size

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onBindViewHolder(holder: LeaveVH, position: Int) {
        val item = list[position]

        holder.binding.txtLeaveType.text = item.leaveType
        holder.binding.txtLeaveDate.text = item.leaveDate
        holder.binding.txtStatus.text = item.status
        when (item.status.lowercase()) {
            "approved" -> holder.binding.txtStatus.setTextColor(
                holder.itemView.context.getColor(android.R.color.holo_green_dark)
            )
            "pending" -> holder.binding.txtStatus.setTextColor(
                holder.itemView.context.getColor(android.R.color.holo_orange_dark)
            )
            "rejected" -> holder.binding.txtStatus.setTextColor(
                holder.itemView.context.getColor(android.R.color.holo_red_dark)
            )
        }


        holder.binding.txtDays.text = if (item.leaveType == "Permission"){"${item.days} Minutes"}else{"${item.days} Day(s)"}


        holder.itemView.setOnClickListener {
            onItemClick(item)
        }

        val firstPart = if (item.leaveType == "Permission"){
            item.leaveDate.split("(")[0]
        } else {
            item.leaveDate.split(" - ")[0] // Extract "2025-12-12"
        }

        var leaveDate: LocalDate? = null
        try {
            leaveDate = LocalDate.parse(firstPart)
        } catch (e: Exception) {
            e.printStackTrace()
        }

        val today = LocalDate.now()

        if (leaveDate != null && leaveDate.isAfter(today))
            holder.binding.txtUpcoming.visibility = View.VISIBLE
        else
            holder.binding.txtUpcoming.visibility = View.GONE

        if (item.status.lowercase().equals("pending", true)) {
            holder.binding.btnCancel.visibility = View.VISIBLE
            holder.binding.btnCancel.setOnClickListener {
                onCancelClick(item)
            }
        } else {
            holder.binding.btnCancel.visibility = View.GONE
        }

    }


}
