package com.kbs.kbsintranett;

import android.graphics.Color;
import android.graphics.Paint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

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

    private List<TaskItem> tasks;
    private OnTaskClickListener listener;
    private String currentUserEmail;

    public interface OnTaskClickListener {
        void onTaskClick(TaskItem task);
        void onStatusChanged(TaskItem task, boolean isDone);
    }

    public TaskAdapter(List<TaskItem> tasks, OnTaskClickListener listener) {
        this.tasks = tasks;
        this.listener = listener;
        this.currentUserEmail = UserManager.getInstance().getUserEmail();
    }

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

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        TaskItem task = tasks.get(position);
        holder.title.setText(task.getTitle());

        if (task.getDueDate() > 0) {
            SimpleDateFormat sdf = new SimpleDateFormat("dd. MMM", Locale.getDefault());
            holder.date.setText("Frist: " + sdf.format(new Date(task.getDueDate())));
        } else {
            holder.date.setText("Ingen frist");
        }

        if (task.getCreatedByEmail() != null && !task.getCreatedByEmail().equalsIgnoreCase(currentUserEmail)) {
            holder.creator.setText("Tildelt av: " + task.getCreatedByName());
            holder.creator.setVisibility(View.VISIBLE);
        } else {
            holder.creator.setVisibility(View.GONE);
        }

        // SJEKK: Er jeg en deltaker?
        boolean isParticipant = task.isUserParticipant(currentUserEmail);

        if (isParticipant) {
            // Hvis jeg er deltaker: Vis checkbox og la meg endre MIN status
            holder.checkBox.setVisibility(View.VISIBLE);
            boolean myStatus = task.getParticipantStatus(currentUserEmail);
            holder.checkBox.setOnCheckedChangeListener(null); // Hindre trigging ved resirkulering
            holder.checkBox.setChecked(myStatus);
            holder.checkBox.setOnClickListener(v -> listener.onStatusChanged(task, holder.checkBox.isChecked()));
        } else {
            // Hvis jeg IKKE er deltaker (f.eks. Admin som ser på "Alle"):
            // Skjul checkboxen i listen. Admin må åpne detaljer for å endre andres status.
            holder.checkBox.setVisibility(View.INVISIBLE);
            holder.checkBox.setOnClickListener(null);
        }

        long now = System.currentTimeMillis();
        // Sjekk overtid (kun hvis frist er satt)
        // Er jeg ikke deltaker, sjekker vi om hele oppgaven er ferdig
        boolean isDoneToCheck = isParticipant ? task.getParticipantStatus(currentUserEmail) : task.isFullyCompleted();
        boolean isOverdue = task.getDueDate() > 0 && task.getDueDate() < now && !task.isFullyCompleted() && !isDoneToCheck;

        if (isOverdue) {
            holder.cardView.setCardBackgroundColor(ContextCompat.getColor(holder.itemView.getContext(), R.color.kbs_soft_light_pink_beige));
            holder.date.setTextColor(ContextCompat.getColor(holder.itemView.getContext(), R.color.kbs_logo_accent_red));
            SimpleDateFormat sdf = new SimpleDateFormat("dd. MMM", Locale.getDefault());
            holder.date.setText("FORFALT: " + sdf.format(new Date(task.getDueDate())));
        } else {
            holder.cardView.setCardBackgroundColor(Color.WHITE);
            holder.date.setTextColor(ContextCompat.getColor(holder.itemView.getContext(), R.color.kbs_muted_blue_gray));
        }

        if (isDoneToCheck || task.isFullyCompleted()) {
            holder.title.setPaintFlags(holder.title.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            holder.title.setTextColor(Color.GRAY);
            holder.cardView.setCardBackgroundColor(Color.parseColor("#F5F5F5"));
        } else if (!isOverdue) {
            holder.title.setPaintFlags(holder.title.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
            holder.title.setTextColor(Color.BLACK);
        }

        int total = task.getAssigneeStatus().size();
        int done = 0;
        for (Boolean b : task.getAssigneeStatus().values()) if (b) done++;
        holder.progress.setText("Fremdrift: " + done + "/" + total);

        holder.itemView.setOnClickListener(v -> listener.onTaskClick(task));
    }

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

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView title, date, creator, progress;
        CheckBox checkBox;
        CardView cardView;
        ViewHolder(View v) {
            super(v);
            title = v.findViewById(R.id.task_title);
            date = v.findViewById(R.id.task_date);
            creator = v.findViewById(R.id.task_creator);
            progress = v.findViewById(R.id.task_progress);
            checkBox = v.findViewById(R.id.task_checkbox);
            cardView = (CardView) v;
        }
    }
}