package com.b2lmobitech.fieldcloudhrms

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.b2lmobitech.fieldcloudhrms.databinding.ItemAttendanceCardBinding

class AttendanceAdapter(private var list: List<AttendanceModel>,
                        private val onItemClick: (AttendanceModel) -> Unit
) :
    RecyclerView.Adapter<AttendanceAdapter.AttendanceViewHolder>() {

    inner class AttendanceViewHolder(val binding: ItemAttendanceCardBinding) :
        RecyclerView.ViewHolder(binding.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AttendanceViewHolder {
        return AttendanceViewHolder(
            ItemAttendanceCardBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
        )
    }

    override fun onBindViewHolder(holder: AttendanceViewHolder, position: Int) {
        val item = list[position]
        if (item.date.length > 2) {
            holder.binding.txtDate.text = item.date.substring(8,10)
        }else {
            holder.binding.txtDate.text = item.date
        }
        holder.binding.txtDay.text = item.day
        holder.binding.txtInTime.text = item.inTime
        holder.binding.txtOutTime.text = item.outTime
        holder.binding.txtStatus.text = item.status
        holder.binding.txtShiftTime.text = "${item.shiftname} (${item.shiftfrom} - ${item.shiftto})"

        val context = holder.itemView.context

        val colorRes = when (item.status.uppercase()) {
            "LEAVE" -> R.color.black
            "UPCOMING" -> R.color.status_upcoming
            "ABSENT" -> R.color.status_absent
            "INCOMPLETE" -> R.color.status_inprogress
            "PRESENT" -> R.color.status_present
            else -> android.R.color.darker_gray
        }

        holder.binding.txtStatus.setTextColor(context.getColor(colorRes))

        holder.itemView.setOnClickListener {
            onItemClick(item)   // ← pass clicked item
        }

    }

    fun updateData(newList: List<AttendanceModel>) {
        list = newList   // assigns new week data
        notifyDataSetChanged()
    }

    override fun getItemCount() = list.size
}
