package com.kbs.kbsintranett;

import android.Manifest;
import android.content.pm.PackageManager;
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.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
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.swiperefreshlayout.widget.SwipeRefreshLayout;
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 retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class HomeFragment extends Fragment {
    private ActivityResultLauncher<String> requestPermissionLauncher;
    private RecyclerView calendarRecycler;
    private RecyclerView newsRecycler;
    private ProgressBar mainProgressBar;
    private SwipeRefreshLayout swipeRefreshLayout;

    private int activeNetworkCalls = 0;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestPermissionLauncher = registerForActivityResult(
                new ActivityResultContracts.RequestPermission(),
                isGranted -> {
                    if (calendarRecycler != null) {
                        refreshData();
                    }
                }
        );
        // GAMMEL METODE FJERNET HERFRA (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);

        mainProgressBar = view.findViewById(R.id.main_loading_spinner);
        if (mainProgressBar != null) mainProgressBar.setVisibility(View.VISIBLE);

        swipeRefreshLayout = view.findViewById(R.id.swipe_refresh_home);
        swipeRefreshLayout.setOnRefreshListener(this::refreshData);

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

        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 (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);
            }
        }

        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);
            });
        }

        refreshData();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (activeNetworkCalls == 0) {
            refreshData();
        }
    }

    private void refreshData() {
        activeNetworkCalls = 2;

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

        fetchNewsFromWordpress(newsRecycler);
    }

    private void checkLoadingComplete() {
        activeNetworkCalls--;
        if (activeNetworkCalls <= 0) {
            activeNetworkCalls = 0;
            if (mainProgressBar != null) mainProgressBar.setVisibility(View.GONE);
            if (swipeRefreshLayout != null) swipeRefreshLayout.setRefreshing(false);
        }
    }

    private void fetchCalendarEvents(RecyclerView recyclerView) {
        new Thread(() -> {
            List<CalendarEvent> deviceEvents = CalendarManager.getDeviceEvents(getContext(), true);
            new Handler(Looper.getMainLooper()).post(() -> fetchApiEvents(recyclerView, deviceEvents));
        }).start();
    }

    private void fetchApiEvents(RecyclerView recyclerView, 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;

                List<CalendarEvent> apiEvents = new ArrayList<>();
                if (response.isSuccessful() && response.body() != null) {
                    apiEvents = response.body();

                    CacheManager.saveCalendarEvents(getContext(), apiEvents);

                    for (CalendarEvent e : apiEvents) {
                        CalendarManager.formatEventForUI(e);
                    }
                } else {
                    apiEvents = CacheManager.getCachedCalendarEvents(getContext());
                    for (CalendarEvent e : apiEvents) CalendarManager.formatEventForUI(e);
                    if (!apiEvents.isEmpty()) {
                        Toast.makeText(getContext(), "Server utilgjengelig. Viser lagret kalender.", Toast.LENGTH_SHORT).show();
                    }
                }

                updateCalendarUI(recyclerView, apiEvents, deviceEvents);
                checkLoadingComplete();
            }

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

                List<CalendarEvent> cachedApiEvents = CacheManager.getCachedCalendarEvents(getContext());
                for (CalendarEvent e : cachedApiEvents) CalendarManager.formatEventForUI(e);

                if (!cachedApiEvents.isEmpty()) {
                    Toast.makeText(getContext(), "Ingen nettverk. Viser lagret kalender.", Toast.LENGTH_SHORT).show();
                }

                updateCalendarUI(recyclerView, cachedApiEvents, deviceEvents);
                checkLoadingComplete();
            }
        });
    }

    private void updateCalendarUI(RecyclerView recyclerView, List<CalendarEvent> apiEvents, List<CalendarEvent> deviceEvents) {
        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> topEvents = new ArrayList<>();
        for(int i=0; i<Math.min(upcomingEvents.size(), 5); i++) {
            topEvents.add(upcomingEvents.get(i));
        }

        recyclerView.setAdapter(new CalendarAdapter(topEvents, event -> {
            CalendarDetailsBottomSheet sheet = new CalendarDetailsBottomSheet(event);
            sheet.setOnEventChangeListener(HomeFragment.this::refreshData);
            sheet.show(getParentFragmentManager(), "CalendarDetails");
        }));
    }

    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;

                List<WpPost> postsToShow = new ArrayList<>();

                if (response.isSuccessful() && response.body() != null) {
                    postsToShow = response.body();
                    CacheManager.saveNewsPosts(getContext(), postsToShow);
                } else {
                    postsToShow = CacheManager.getCachedNewsPosts(getContext());
                    if (!postsToShow.isEmpty()) {
                        Toast.makeText(getContext(), "Server utilgjengelig. Viser lagrede nyheter.", Toast.LENGTH_SHORT).show();
                    }
                }

                updateNewsUI(recyclerView, postsToShow);
                checkLoadingComplete();
            }

            @Override
            public void onFailure(Call<List<WpPost>> call, Throwable t) {
                if (getContext() == null) return;

                List<WpPost> cachedPosts = CacheManager.getCachedNewsPosts(getContext());
                if (!cachedPosts.isEmpty()) {
                    Toast.makeText(getContext(), "Ingen nettverk. Viser lagrede nyheter.", Toast.LENGTH_SHORT).show();
                }

                updateNewsUI(recyclerView, cachedPosts);
                checkLoadingComplete();
            }
        });
    }

    private void updateNewsUI(RecyclerView recyclerView, List<WpPost> posts) {
        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 : posts) {
            try {
                Date date = rawFormat.parse(post.date);
                post.date = targetFormat.format(date);
            } catch (Exception e) {}
        }

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