package com.kbs.kbsintranett;

import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

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

    public static final int TYPE_CREATE_BUTTON = 1;
    public static final int TYPE_SECTION_TITLE = 2;
    public static final int TYPE_CALENDAR_ITEM = 3;
    public static final int TYPE_NEWS_ITEM = 4;
    public static final int TYPE_TASK_ITEM = 5;
    public static final int TYPE_EMPTY_TASKS = 6;

    private final List<Object> items;
    private final OnHomeClickListener listener;

    public interface OnHomeClickListener {
        void onCreateEventClick();
        void onViewAllCalendarClick();
        void onViewAllNewsClick();
        void onViewAllTasksClick();
        void onCalendarItemClick(CalendarEvent event);
        void onNewsItemClick(WpPost post);
        void onTaskItemClick(TaskItem task);
        void onTaskStatusChanged(TaskItem task, boolean isDone);
    }

    public HomeAdapter(List<Object> items, OnHomeClickListener listener) {
        this.items = items;
        this.listener = listener;
    }

    @Override
    public int getItemViewType(int position) {
        Object item = items.get(position);
        if (item instanceof CreateButtonItem) return TYPE_CREATE_BUTTON;
        if (item instanceof SectionTitleItem) return TYPE_SECTION_TITLE;
        if (item instanceof CalendarEvent) return TYPE_CALENDAR_ITEM;
        if (item instanceof WpPost) return TYPE_NEWS_ITEM;
        if (item instanceof TaskItem) return TYPE_TASK_ITEM;
        if (item instanceof EmptyTasksItem) return TYPE_EMPTY_TASKS;
        return -1;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        switch (viewType) {
            case TYPE_CREATE_BUTTON:
                return new CreateButtonViewHolder(inflater.inflate(R.layout.item_home_create_btn, parent, false));
            case TYPE_SECTION_TITLE:
                return new SectionTitleViewHolder(inflater.inflate(R.layout.item_home_section_title, parent, false));
            case TYPE_CALENDAR_ITEM:
                return new CalendarViewHolder(inflater.inflate(R.layout.item_calendar, parent, false));
            case TYPE_TASK_ITEM:
                return new TaskViewHolder(inflater.inflate(R.layout.item_task, parent, false));
            case TYPE_EMPTY_TASKS:
                return new EmptyViewHolder(inflater.inflate(R.layout.item_home_empty_tasks, parent, false));
            case TYPE_NEWS_ITEM:
                return new NewsViewHolder(inflater.inflate(R.layout.item_news, parent, false));
            default:
                throw new IllegalArgumentException("Ugyldig viewType");
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        Object item = items.get(position);

        if (holder instanceof CreateButtonViewHolder) {
            ((CreateButtonViewHolder) holder).btnCreate.setOnClickListener(v -> listener.onCreateEventClick());
        }
        else if (holder instanceof SectionTitleViewHolder) {
            SectionTitleItem section = (SectionTitleItem) item;
            SectionTitleViewHolder vh = (SectionTitleViewHolder) holder;
            vh.title.setText(section.title);
            vh.btnViewAll.setOnClickListener(v -> {
                if (section.type == SectionTitleItem.TYPE_CALENDAR) listener.onViewAllCalendarClick();
                else if (section.type == SectionTitleItem.TYPE_TASKS) listener.onViewAllTasksClick();
                else listener.onViewAllNewsClick();
            });
        }
        else if (holder instanceof CalendarViewHolder) {
            CalendarEvent event = (CalendarEvent) item;
            CalendarViewHolder vh = (CalendarViewHolder) holder;
            vh.day.setText(event.getDay());
            vh.month.setText(event.getMonth());
            vh.time.setText(event.getTime());
            vh.title.setText(event.getTitle());
            boolean isPrivate = event.getDescription() != null && event.getDescription().contains("#deltakere:");
            try {
                int color = Color.parseColor(isPrivate ? "#673AB7" : event.getCalendarColor());
                vh.dateBox.setBackgroundTintList(ColorStateList.valueOf(color));
            } catch (Exception e) {
                vh.dateBox.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#0069B3")));
            }
            vh.itemView.setOnClickListener(v -> listener.onCalendarItemClick(event));
        }
        else if (holder instanceof TaskViewHolder) {
            TaskItem task = (TaskItem) item;
            TaskViewHolder vh = (TaskViewHolder) holder;
            vh.title.setText(task.getTitle());

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

            String myEmail = UserManager.getInstance().getUserEmail();
            boolean myStatus = task.getParticipantStatus(myEmail);
            vh.checkBox.setChecked(myStatus);

            long now = System.currentTimeMillis();
            boolean isOverdue = task.getDueDate() > 0 && task.getDueDate() < now && !task.isFullyCompleted() && !myStatus;

            if (isOverdue) {
                vh.cardView.setCardBackgroundColor(ContextCompat.getColor(vh.itemView.getContext(), R.color.kbs_soft_light_pink_beige));
                vh.date.setTextColor(ContextCompat.getColor(vh.itemView.getContext(), R.color.kbs_logo_accent_red));
            } else {
                vh.cardView.setCardBackgroundColor(Color.WHITE);
                vh.date.setTextColor(ContextCompat.getColor(vh.itemView.getContext(), R.color.kbs_muted_blue_gray));
            }

            // --- REINTRODUSERT FREMDRIFTSBEREGNING ---
            int total = task.getAssigneeStatus().size();
            int done = 0;
            for (Boolean isFinished : task.getAssigneeStatus().values()) {
                if (isFinished) done++;
            }
            vh.progress.setText("Fremdrift: " + done + "/" + total);
            // ------------------------------------------

            vh.checkBox.setOnClickListener(v -> listener.onTaskStatusChanged(task, vh.checkBox.isChecked()));
            vh.itemView.setOnClickListener(v -> listener.onTaskItemClick(task));
        }
        else if (holder instanceof NewsViewHolder) {
            WpPost post = (WpPost) item;
            NewsViewHolder vh = (NewsViewHolder) holder;
            vh.title.setText(post.getTitleStr());
            vh.excerpt.setText(post.getExcerptStr());
            vh.date.setText(post.date);
            String cat = post.getCategoryName();
            vh.category.setText(cat);
            vh.category.setVisibility(cat.isEmpty() ? View.GONE : View.VISIBLE);
            String imgUrl = post.getFeaturedImageUrl();
            if (imgUrl != null) {
                vh.image.setVisibility(View.VISIBLE);
                Glide.with(vh.image.getContext()).load(imgUrl).transition(DrawableTransitionOptions.withCrossFade()).centerCrop().into(vh.image);
            } else {
                vh.image.setVisibility(View.GONE);
            }
            vh.itemView.setOnClickListener(v -> listener.onNewsItemClick(post));
        }
    }

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

    // --- VIEW HOLDERS ---
    static class CreateButtonViewHolder extends RecyclerView.ViewHolder {
        Button btnCreate;
        CreateButtonViewHolder(View v) { super(v); btnCreate = v.findViewById(R.id.btn_create_event); }
    }

    static class SectionTitleViewHolder extends RecyclerView.ViewHolder {
        TextView title, btnViewAll;
        SectionTitleViewHolder(View v) { super(v); title = v.findViewById(R.id.txt_section_title); btnViewAll = v.findViewById(R.id.btn_view_all); }
    }

    static class CalendarViewHolder extends RecyclerView.ViewHolder {
        TextView day, month, title, time;
        LinearLayout dateBox;
        CalendarViewHolder(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);
        }
    }

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

    static class NewsViewHolder extends RecyclerView.ViewHolder {
        TextView title, excerpt, date, category;
        ImageView image;
        NewsViewHolder(View v) {
            super(v);
            title = v.findViewById(R.id.news_title);
            excerpt = v.findViewById(R.id.news_excerpt);
            date = v.findViewById(R.id.news_date);
            category = v.findViewById(R.id.news_category);
            image = v.findViewById(R.id.news_image);
        }
    }

    static class EmptyViewHolder extends RecyclerView.ViewHolder {
        EmptyViewHolder(View v) { super(v); }
    }

    public static class CreateButtonItem {}
    public static class EmptyTasksItem {}
    public static class SectionTitleItem {
        public static final int TYPE_CALENDAR = 0;
        public static final int TYPE_NEWS = 1;
        public static final int TYPE_TASKS = 2;
        String title; int type;
        public SectionTitleItem(String t, int type) { this.title = t; this.type = type; }
    }
}