package com.kbs.kbsintranett;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.JsonElement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class TasksFragment extends Fragment implements TaskAdapter.OnTaskClickListener {

    private RecyclerView recyclerView;
    private TaskAdapter adapter;
    private TabLayout tabLayout;
    private SwipeRefreshLayout swipeRefresh;
    private CheckBox cbShowCompleted;
    private List<TaskItem> allTasks = new ArrayList<>();
    private String myEmail;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_tasks, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        myEmail = UserManager.getInstance().getUserEmail();
        tabLayout = view.findViewById(R.id.task_tabs);
        recyclerView = view.findViewById(R.id.recycler_tasks);
        swipeRefresh = view.findViewById(R.id.swipe_refresh_tasks);
        cbShowCompleted = view.findViewById(R.id.cb_show_completed);

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        setupTabs();

        FloatingActionButton fab = view.findViewById(R.id.fab_add_task);
        fab.setOnClickListener(v -> {
            AddTaskBottomSheet dialog = new AddTaskBottomSheet();
            dialog.setOnTaskAddedListener(new AddTaskBottomSheet.OnTaskAddedListener() {
                @Override
                public void onTaskAdded(TaskItem task) {
                    allTasks.add(0, task);
                    saveAndSync();
                }

                @Override
                public void onTaskUpdated(TaskItem task) {
                    saveAndSync();
                }
            });
            dialog.show(getChildFragmentManager(), "AddTask");
        });

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override public void onTabSelected(TabLayout.Tab tab) {
                updateFilterUI(tab.getPosition());
                filterAndDisplay();
            }
            @Override public void onTabUnselected(TabLayout.Tab tab) {}
            @Override public void onTabReselected(TabLayout.Tab tab) {}
        });

        cbShowCompleted.setOnCheckedChangeListener((buttonView, isChecked) -> filterAndDisplay());

        swipeRefresh.setOnRefreshListener(this::fetchTasksFromServer);

        allTasks = CacheManager.getTasks(getContext());
        updateFilterUI(tabLayout.getSelectedTabPosition());
        filterAndDisplay();
        fetchTasksFromServer();
    }

    private void setupTabs() {
        tabLayout.removeAllTabs();
        tabLayout.addTab(tabLayout.newTab().setText("Mine"));
        tabLayout.addTab(tabLayout.newTab().setText("Fullførte"));
        tabLayout.addTab(tabLayout.newTab().setText("Tildelt andre"));
        if (UserManager.getInstance().isEditorOrAbove()) {
            tabLayout.addTab(tabLayout.newTab().setText("Alle"));
        }
    }

    private void updateFilterUI(int tabIndex) {
        if (tabIndex == 3) {
            cbShowCompleted.setVisibility(View.VISIBLE);
        } else {
            cbShowCompleted.setVisibility(View.GONE);
        }
    }

    private void fetchTasksFromServer() {
        swipeRefresh.setRefreshing(true);
        RetrofitClient.getApiService().getTasks().enqueue(new Callback<List<TaskItem>>() {
            @Override
            public void onResponse(Call<List<TaskItem>> call, Response<List<TaskItem>> response) {
                swipeRefresh.setRefreshing(false);
                if (response.isSuccessful() && response.body() != null) {
                    allTasks = response.body();
                    CacheManager.saveTasks(getContext(), allTasks);
                    filterAndDisplay();
                }
            }
            @Override
            public void onFailure(Call<List<TaskItem>> call, Throwable t) {
                swipeRefresh.setRefreshing(false);
                Toast.makeText(getContext(), "Kunne ikke synkronisere oppgaver", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void filterAndDisplay() {
        List<TaskItem> filtered = new ArrayList<>();
        int selectedTab = tabLayout.getSelectedTabPosition();

        for (TaskItem t : allTasks) {
            boolean isParticipant = t.isUserParticipant(myEmail);
            boolean isCreator = t.getCreatedByEmail().equalsIgnoreCase(myEmail);
            boolean iHaveDoneIt = t.getParticipantStatus(myEmail);
            boolean hasOtherParticipants = false;
            for (String email : t.getAssigneeStatus().keySet()) {
                if (!email.equalsIgnoreCase(myEmail)) { hasOtherParticipants = true; break; }
            }

            // NYTT: Sjekk dynamisk om ALLE deltakerne har fullført oppgaven
            boolean allParticipantsFinished = true;
            if (t.getAssigneeStatus().isEmpty()) {
                allParticipantsFinished = false;
            } else {
                for (Boolean isDone : t.getAssigneeStatus().values()) {
                    if (!isDone) {
                        allParticipantsFinished = false;
                        break;
                    }
                }
            }

            // En oppgave er "helt ferdig" hvis flagget er satt ELLER alle har krysset av
            boolean effectivelyFinished = t.isFullyCompleted() || allParticipantsFinished;

            // Oppdater objektet slik at det lagres riktig neste gang (valgfritt men lurt)
            if (effectivelyFinished && !t.isFullyCompleted()) {
                t.setFullyCompleted(true);
            }

            switch (selectedTab) {
                case 0: // MINE
                    if (isParticipant && !iHaveDoneIt && !t.isFullyCompleted()) filtered.add(t);
                    break;
                case 1: // FULLFØRTE
                    if (t.isFullyCompleted() || (isParticipant && iHaveDoneIt)) filtered.add(t);
                    break;
                case 2: // TILDELT ANDRE
                    if (isCreator && !t.isFullyCompleted() && hasOtherParticipants) filtered.add(t);
                    break;
                case 3: // ALLE (Admin)
                    if (cbShowCompleted.isChecked()) {
                        // Vis alt
                        filtered.add(t);
                    } else {
                        // Vis kun hvis IKKE ferdig
                        if (!effectivelyFinished) filtered.add(t);
                    }
                    break;
            }
        }

        // SORTERING
        Collections.sort(filtered, (t1, t2) -> {
            boolean t1HasDate = t1.getDueDate() > 0;
            boolean t2HasDate = t2.getDueDate() > 0;

            if (selectedTab == 1) {
                if (t1HasDate && !t2HasDate) return -1;
                if (!t1HasDate && t2HasDate) return 1;
                if (!t1HasDate && !t2HasDate) return t1.getTitle().compareToIgnoreCase(t2.getTitle());
                return Long.compare(t2.getDueDate(), t1.getDueDate());
            }
            else {
                if (t1HasDate && !t2HasDate) return -1;
                if (!t1HasDate && t2HasDate) return 1;
                if (!t1HasDate && !t2HasDate) return t1.getTitle().compareToIgnoreCase(t2.getTitle());
                return Long.compare(t1.getDueDate(), t2.getDueDate());
            }
        });

        adapter = new TaskAdapter(filtered, this);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onTaskClick(TaskItem task) {
        TaskDetailsBottomSheet sheet = new TaskDetailsBottomSheet(task, new TaskDetailsBottomSheet.OnTaskChangeListener() {
            @Override public void onTaskChanged() { saveAndSync(); }
            @Override public void onTaskDeleted(TaskItem taskToDelete) {
                allTasks.remove(taskToDelete);
                saveAndSync();
            }
            @Override public void onEditRequested(TaskItem taskToEdit) {
                AddTaskBottomSheet editDialog = new AddTaskBottomSheet();
                editDialog.setTaskToEdit(taskToEdit);
                editDialog.setOnTaskAddedListener(new AddTaskBottomSheet.OnTaskAddedListener() {
                    @Override public void onTaskAdded(TaskItem task) {}
                    @Override public void onTaskUpdated(TaskItem task) {
                        saveAndSync();
                    }
                });
                editDialog.show(getChildFragmentManager(), "EditTask");
            }
        });
        sheet.show(getChildFragmentManager(), "TaskDetails");
    }

    @Override
    public void onStatusChanged(TaskItem task, boolean isDone) {
        task.setParticipantStatus(myEmail, isDone);
        // Her trenger vi ikke logikk for "hasOthers" osv, fordi saveAndSync()
        // kaller filterAndDisplay() som nå regner ut status dynamisk.
        saveAndSync();
    }

    private void saveAndSync() {
        CacheManager.saveTasks(getContext(), allTasks);
        filterAndDisplay(); // Oppdaterer visningen umiddelbart
        RetrofitClient.getApiService().syncTasks(allTasks).enqueue(new Callback<JsonElement>() {
            @Override public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {}
            @Override public void onFailure(Call<JsonElement> call, Throwable t) {}
        });
    }
}