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.ImageView;
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 java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CalendarFullFragment extends Fragment {

    private RecyclerView recyclerView;
    private ProgressBar progressBar;
    private TextView emptyView;
    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);
        ImageView backBtn = view.findViewById(R.id.btn_back_calendar);

        layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);
        backBtn.setOnClickListener(v -> Navigation.findNavController(view).navigateUp());
    }

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

    private void fetchAllEvents() {
        progressBar.setVisibility(View.VISIBLE);

        new Thread(() -> {
            // HER ER ENDRINGEN: isPreview = false (Hent alt)
            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);

                if (allEvents.isEmpty()) {
                    emptyView.setVisibility(View.VISIBLE);
                    recyclerView.setVisibility(View.GONE);
                } else {
                    emptyView.setVisibility(View.GONE);
                    recyclerView.setVisibility(View.VISIBLE);

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

                    scrollToToday(allEvents);
                }
            }

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

                if (!deviceEvents.isEmpty()) {
                    CalendarAdapter adapter = new CalendarAdapter(deviceEvents, event -> {
                        CalendarDetailsBottomSheet sheet = new CalendarDetailsBottomSheet(event);
                        sheet.show(getParentFragmentManager(), "CalendarDetails");
                    });
                    recyclerView.setAdapter(adapter);
                    scrollToToday(deviceEvents);
                } else {
                    emptyView.setText("Ingen hendelser funnet.");
                    emptyView.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void scrollToToday(List<CalendarEvent> events) {
        String today = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
        int scrollIndex = 0;

        for (int i = 0; i < events.size(); i++) {
            String raw = events.get(i).getRawDate();
            if (raw != null && raw.compareTo(today) >= 0) {
                scrollIndex = i;
                break;
            }
        }

        if (scrollIndex > 0) {
            layoutManager.scrollToPositionWithOffset(scrollIndex, 0);
        }
    }
}