package com.kbs.kbsintranett;

import android.content.res.ColorStateList;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;

public class CalendarAdapter extends RecyclerView.Adapter<CalendarAdapter.ViewHolder> {

    private List<CalendarEvent> events;
    private final OnItemClickListener listener;

    public interface OnItemClickListener {
        void onItemClick(CalendarEvent event);
    }

    public CalendarAdapter(List<CalendarEvent> events, OnItemClickListener listener) {
        this.events = events;
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_calendar, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        CalendarEvent event = events.get(position);
        holder.day.setText(event.getDay());
        holder.month.setText(event.getMonth());
        holder.time.setText(event.getTime());
        holder.title.setText(event.getTitle());

        // NYTT: Sett farge på datoboksen
        try {
            int color = Color.parseColor(event.getCalendarColor());
            holder.dateBox.setBackgroundTintList(ColorStateList.valueOf(color));
        } catch (Exception e) {
            // Fallback til standard blå hvis fargekoden er ugyldig
            holder.dateBox.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#0069B3")));
        }

        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onItemClick(event);
            }
        });
    }

    @Override
    public int getItemCount() {
        return events.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView day, month, title, time;
        LinearLayout dateBox; // NYTT

        public ViewHolder(View view) {
            super(view);
            day = view.findViewById(R.id.cal_day);
            month = view.findViewById(R.id.cal_month);
            title = view.findViewById(R.id.cal_title);
            time = view.findViewById(R.id.cal_time);
            dateBox = view.findViewById(R.id.date_box_background); // NYTT
        }
    }
}