package com.kbs.kbsintranett;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CalendarFullFragment extends Fragment {

    private RecyclerView recyclerView;
    private ProgressBar progressBar;
    private TextView emptyView;
    private FloatingActionButton fabAddEvent;
    private LinearLayoutManager layoutManager;

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

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        recyclerView = view.findViewById(R.id.recycler_full_calendar);
        progressBar = view.findViewById(R.id.loading_full_calendar);
        emptyView = view.findViewById(R.id.empty_view_calendar);
        fabAddEvent = view.findViewById(R.id.fab_add_calendar_event);

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

        if (!UserManager.getInstance().getWriteableCalendars().isEmpty() || UserManager.getInstance().isEditorOrAbove()) {
            fabAddEvent.setVisibility(View.VISIBLE);
            fabAddEvent.setOnClickListener(v -> Navigation.findNavController(view).navigate(R.id.navigation_create_event));
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        fetchAllEvents();
    }

    private void fetchAllEvents() {
        progressBar.setVisibility(View.VISIBLE);
        new Thread(() -> {
            List<CalendarEvent> deviceEvents = CalendarManager.getDeviceEvents(getContext(), false);
            new Handler(Looper.getMainLooper()).post(() -> fetchApiEvents(deviceEvents));
        }).start();
    }

    private void fetchApiEvents(List<CalendarEvent> deviceEvents) {
        RetrofitClient.getApiService().getCalendarEvents().enqueue(new Callback<List<CalendarEvent>>() {
            @Override
            public void onResponse(Call<List<CalendarEvent>> call, Response<List<CalendarEvent>> response) {
                if (!isAdded()) return;
                progressBar.setVisibility(View.GONE);

                List<CalendarEvent> apiEvents = new ArrayList<>();
                if (response.isSuccessful() && response.body() != null) {
                    apiEvents = response.body();
                    for (CalendarEvent e : apiEvents) CalendarManager.formatEventForUI(e);
                }

                List<CalendarEvent> allEvents = CalendarManager.mergeAndSort(apiEvents, deviceEvents);
                displaySortedList(allEvents);
            }

            @Override
            public void onFailure(Call<List<CalendarEvent>> call, Throwable t) {
                if (!isAdded()) return;
                progressBar.setVisibility(View.GONE);
                displaySortedList(deviceEvents);
            }
        });
    }

    private void displaySortedList(List<CalendarEvent> events) {
        if (events.isEmpty()) {
            emptyView.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
            return;
        }

        emptyView.setVisibility(View.GONE);
        recyclerView.setVisibility(View.VISIBLE);

        List<Object> itemsWithHeaders = new ArrayList<>();
        String currentYear = "";

        for (CalendarEvent e : events) {
            String year = "Ukjent år";
            if (e.getRawDate() != null && e.getRawDate().length() >= 4) {
                year = e.getRawDate().substring(0, 4);
            }

            if (!year.equals(currentYear)) {
                itemsWithHeaders.add(year);
                currentYear = year;
            }
            itemsWithHeaders.add(e);
        }

        CalendarAdapter adapter = new CalendarAdapter(itemsWithHeaders, event -> {
            CalendarDetailsBottomSheet sheet = new CalendarDetailsBottomSheet(event);
            sheet.setOnEventChangeListener(CalendarFullFragment.this::fetchAllEvents);
            sheet.show(getParentFragmentManager(), "CalendarDetails");
        });
        recyclerView.setAdapter(adapter);
    }
}