package com.kbs.kbsintranett;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class HomeFragment extends Fragment {
    private ActivityResultLauncher<String> requestPermissionLauncher;
    private RecyclerView calendarRecycler;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestPermissionLauncher = registerForActivityResult(
                new ActivityResultContracts.RequestPermission(),
                isGranted -> {
                    if (calendarRecycler != null) {
                        fetchCalendarEvents(calendarRecycler);
                    }
                }
        );
        startNotificationWorker();
    }

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

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

        View profileBtn = view.findViewById(R.id.btn_profile);
        if (profileBtn != null) {
            profileBtn.setOnClickListener(v -> Navigation.findNavController(view).navigate(R.id.navigation_profile));
        }

        // NY LOGIKK: Vis knapp hvis brukeren har tilgang til minst én kalender
        Button btnCreateEvent = view.findViewById(R.id.btn_create_event);
        List<String> writeable = UserManager.getInstance().getWriteableCalendars();

        if (writeable != null && !writeable.isEmpty()) {
            btnCreateEvent.setVisibility(View.VISIBLE);
            btnCreateEvent.setOnClickListener(v -> {
                Navigation.findNavController(view).navigate(R.id.action_home_to_create_event);
            });
        } else {
            btnCreateEvent.setVisibility(View.GONE);
        }

        calendarRecycler = view.findViewById(R.id.recycler_calendar);
        calendarRecycler.setLayoutManager(new LinearLayoutManager(getContext()));
        calendarRecycler.setAdapter(new CalendarAdapter(new ArrayList<>(), event -> {}));

        TextView viewAllCalendar = view.findViewById(R.id.btn_view_all_calendar);
        if (viewAllCalendar != null) {
            viewAllCalendar.setOnClickListener(v -> Navigation.findNavController(view).navigate(R.id.action_home_to_calendarFull));
        }

        if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.READ_CALENDAR) == PackageManager.PERMISSION_GRANTED) {
            fetchCalendarEvents(calendarRecycler);
        } else {
            requestPermissionLauncher.launch(Manifest.permission.READ_CALENDAR);
        }

        if (android.os.Build.VERSION.SDK_INT >= 33) {
            if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {}).launch(Manifest.permission.POST_NOTIFICATIONS);
            }
        }

        RecyclerView newsRecycler = view.findViewById(R.id.recycler_news);
        newsRecycler.setLayoutManager(new LinearLayoutManager(getContext()));
        newsRecycler.setNestedScrollingEnabled(false);
        newsRecycler.setAdapter(new NewsAdapter(new ArrayList<>(), item -> {}));

        TextView viewAllNews = view.findViewById(R.id.btn_view_all_news);
        if (viewAllNews != null) {
            viewAllNews.setOnClickListener(v -> {
                Navigation.findNavController(view).navigate(R.id.action_home_to_newsFull);
            });
        }

        fetchNewsFromWordpress(newsRecycler);
    }

    private void fetchCalendarEvents(RecyclerView recyclerView) {
        List<CalendarEvent> deviceEvents = CalendarManager.getDeviceEvents(getContext());

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

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

                List<CalendarEvent> merged = CalendarManager.mergeAndSort(apiEvents, deviceEvents);
                List<CalendarEvent> upcomingEvents = new ArrayList<>();
                String today = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());

                for (CalendarEvent e : merged) {
                    if (e.getRawDate() != null && e.getRawDate().compareTo(today) >= 0) {
                        upcomingEvents.add(e);
                    }
                }

                List<CalendarEvent> top5 = new ArrayList<>();
                for(int i=0; i<Math.min(upcomingEvents.size(), 5); i++) {
                    top5.add(upcomingEvents.get(i));
                }

                recyclerView.setAdapter(new CalendarAdapter(top5, event -> {
                    CalendarDetailsBottomSheet sheet = new CalendarDetailsBottomSheet(event);
                    sheet.show(getParentFragmentManager(), "CalendarDetails");
                }));
            }

            @Override
            public void onFailure(Call<List<CalendarEvent>> call, Throwable t) {
                if (!isAdded()) return;
                if (!deviceEvents.isEmpty()) {
                    List<CalendarEvent> top5 = new ArrayList<>();
                    for(int i=0; i<Math.min(deviceEvents.size(), 5); i++) top5.add(deviceEvents.get(i));
                    recyclerView.setAdapter(new CalendarAdapter(top5, event -> {
                        CalendarDetailsBottomSheet sheet = new CalendarDetailsBottomSheet(event);
                        sheet.show(getParentFragmentManager(), "CalendarDetails");
                    }));
                } else {
                    List<CalendarEvent> errorList = new ArrayList<>();
                    errorList.add(new CalendarEvent("Kunne ikke laste kalender", "Sjekk nettverk", "!", "OBS", ""));
                    recyclerView.setAdapter(new CalendarAdapter(errorList, null));
                }
            }
        });
    }

    private void fetchNewsFromWordpress(RecyclerView recyclerView) {
        WordPressApiService apiService = RetrofitClient.getApiService();
        apiService.getPosts().enqueue(new Callback<List<WpPost>>() {
            @Override
            public void onResponse(Call<List<WpPost>> call, Response<List<WpPost>> response) {
                if (getContext() == null) return;

                if (response.isSuccessful() && response.body() != null) {
                    List<WpPost> wpPosts = response.body();
                    SimpleDateFormat rawFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault());
                    rawFormat.setTimeZone(TimeZone.getTimeZone("Europe/Oslo"));
                    SimpleDateFormat targetFormat = new SimpleDateFormat("dd. MMM yyyy", Locale.getDefault());
                    targetFormat.setTimeZone(TimeZone.getTimeZone("Europe/Oslo"));

                    for (WpPost post : wpPosts) {
                        try {
                            Date date = rawFormat.parse(post.date);
                            post.date = targetFormat.format(date);
                        } catch (Exception e) {}
                    }

                    NewsAdapter adapter = new NewsAdapter(wpPosts, post -> {
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("post_data", post);
                        Navigation.findNavController(getView()).navigate(R.id.action_home_to_newsDetail, bundle);
                    });
                    recyclerView.setAdapter(adapter);
                }
            }

            @Override
            public void onFailure(Call<List<WpPost>> call, Throwable t) {
                if (getContext() == null) return;
                recyclerView.setAdapter(new NewsAdapter(new ArrayList<>(), null));
            }
        });
    }

    private void startNotificationWorker() {
        PeriodicWorkRequest notifRequest =
                new PeriodicWorkRequest.Builder(NotificationWorker.class, 15, TimeUnit.MINUTES)
                        .build();
        WorkManager.getInstance(requireContext()).enqueue(notifRequest);
    }
}