package com.kbs.kbsintranett;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.google.android.material.switchmaterial.SwitchMaterial;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;

public class TaskDetailsBottomSheet extends BottomSheetDialogFragment {

    private TaskItem task;
    private OnTaskChangeListener listener;

    public interface OnTaskChangeListener {
        void onTaskChanged();
        void onTaskDeleted(TaskItem task);
        void onEditRequested(TaskItem task);
    }

    public TaskDetailsBottomSheet(TaskItem task, OnTaskChangeListener listener) {
        this.task = task;
        this.listener = listener;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.bottom_sheet_task_details, container, false);

        TextView title = v.findViewById(R.id.detail_task_title);
        TextView date = v.findViewById(R.id.detail_task_date);
        TextView desc = v.findViewById(R.id.detail_task_desc);
        LinearLayout participantsContainer = v.findViewById(R.id.container_participants_status);
        SwitchMaterial switchNotify = v.findViewById(R.id.switch_notifications);
        LinearLayout ownerActions = v.findViewById(R.id.layout_owner_actions);
        Button btnDelete = v.findViewById(R.id.btn_delete_task);
        Button btnEdit = v.findViewById(R.id.btn_edit_task);
        Button btnClose = v.findViewById(R.id.btn_close_details); // NYTT

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

        if (task.getDescription() != null && !task.getDescription().isEmpty()) {
            desc.setText(task.getDescription());
            desc.setVisibility(View.VISIBLE);
        }

        participantsContainer.removeAllViews();
        UserManager userManager = UserManager.getInstance();
        String myEmail = userManager.getUserEmail();

        boolean canManageOthers = task.getCreatedByEmail().equalsIgnoreCase(myEmail) || userManager.isAdmin();

        for (Map.Entry<String, Boolean> entry : task.getAssigneeStatus().entrySet()) {
            String email = entry.getKey();
            boolean isDone = entry.getValue();

            if (canManageOthers) {
                CheckBox cb = new CheckBox(getContext());
                cb.setText(email + (isDone ? " (Fullført)" : ""));
                cb.setChecked(isDone);

                if (isDone) cb.setTextColor(getResources().getColor(android.R.color.darker_gray));
                else cb.setTextColor(getResources().getColor(R.color.black));

                cb.setOnCheckedChangeListener((buttonView, isChecked) -> {
                    task.setParticipantStatus(email, isChecked);

                    cb.setText(email + (isChecked ? " (Fullført)" : ""));
                    if (isChecked) cb.setTextColor(getResources().getColor(android.R.color.darker_gray));
                    else cb.setTextColor(getResources().getColor(R.color.black));

                    if (listener != null) listener.onTaskChanged();

                    // Sjekk om alle er ferdige, i så fall lukk vinduet
                    if (isChecked && areAllParticipantsFinished()) {
                        dismiss();
                    }
                });
                participantsContainer.addView(cb);

            } else {
                TextView t = new TextView(getContext());
                String status = isDone ? "✅ Fullført" : "⏳ Pågår";
                t.setText("• " + email + ": " + status);
                t.setPadding(0, 8, 0, 8);
                t.setTextSize(14);
                participantsContainer.addView(t);
            }
        }

        switchNotify.setChecked(task.isNotificationsEnabled());
        switchNotify.setOnCheckedChangeListener((btn, isChecked) -> {
            task.setNotificationsEnabled(isChecked);
            if (listener != null) listener.onTaskChanged();
        });

        if (canManageOthers) {
            ownerActions.setVisibility(View.VISIBLE);
            btnDelete.setOnClickListener(view -> {
                if (listener != null) listener.onTaskDeleted(task);
                dismiss();
            });
            btnEdit.setOnClickListener(view -> {
                if (listener != null) listener.onEditRequested(task);
                dismiss();
            });
        } else {
            ownerActions.setVisibility(View.GONE);
        }

        // NYTT: Lukk-knapp funksjonalitet
        btnClose.setOnClickListener(view -> dismiss());

        return v;
    }

    private boolean areAllParticipantsFinished() {
        for (Boolean isDone : task.getAssigneeStatus().values()) {
            if (!isDone) return false;
        }
        return true;
    }
}