package com.kbs.kbsintranett;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "FCMService";
    private static final String CHANNEL_ID = "kbs_calendar_channel";

    @Override
    public void onNewToken(@NonNull String token) {
        super.onNewToken(token);
        AuthRepository.updateDeviceToken(token);
    }

    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        // 1. DATA PAYLOAD (Bakgrunnsoppdatering)
        if (remoteMessage.getData().size() > 0) {
            String forceRefresh = remoteMessage.getData().get("force_refresh");
            String type = remoteMessage.getData().get("type"); // "tasks_update", "news_update", "calendar_update"

            if ("true".equalsIgnoreCase(forceRefresh)) {
                Log.d(TAG, "Mottok force_refresh. Type: " + type);

                // Uansett hva det er, ugyldiggjør cachen slik at neste gang brukeren åpner appen, hentes ferske data.
                if ("news_update".equals(type)) {
                    CacheManager.invalidateCache(getApplicationContext(), "news");
                } else if ("tasks_update".equals(type)) {
                    CacheManager.invalidateCache(getApplicationContext(), "tasks");
                    updateTasksInBackground(); // Hent oppgaver med en gang i bakgrunnen
                } else {
                    // Kalender eller generelt
                    CacheManager.invalidateCache(getApplicationContext(), "calendar");
                    updateCalendarAndAlarms();
                }
            }
        }

        // 2. NOTIFICATION PAYLOAD (Synlig varsel - Nyheter etc)
        // Android viser disse automatisk når appen er i bakgrunnen.
        // Denne koden kjører hvis appen er i forgrunnen, eller hvis meldingen kun er "Data" og vi vil lage varsel manuelt.
        if (remoteMessage.getNotification() != null) {
            showNotification(
                    remoteMessage.getNotification().getTitle(),
                    remoteMessage.getNotification().getBody()
            );
        }
    }

    private void updateCalendarAndAlarms() {
        RetrofitClient.getApiService().getCalendarEvents().enqueue(new Callback<List<CalendarEvent>>() {
            @Override
            public void onResponse(Call<List<CalendarEvent>> call, Response<List<CalendarEvent>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    CacheManager.saveCalendarEvents(getApplicationContext(), response.body());
                    AlarmScheduler.scheduleAlarmsForEvents(getApplicationContext(), response.body());
                }
            }
            @Override public void onFailure(Call<List<CalendarEvent>> call, Throwable t) {}
        });
    }

    private void updateTasksInBackground() {
        // Henter oppgaver stille i bakgrunnen slik at de er klare når brukeren åpner appen
        RetrofitClient.getApiService().getTasks().enqueue(new Callback<List<TaskItem>>() {
            @Override
            public void onResponse(Call<List<TaskItem>> call, Response<List<TaskItem>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    CacheManager.saveTasks(getApplicationContext(), response.body());
                }
            }
            @Override public void onFailure(Call<List<TaskItem>> call, Throwable t) {}
        });
    }

    private void showNotification(String title, String message) {
        createNotificationChannel();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
        }

        Intent tapIntent = new Intent(this, MainActivity.class);
        tapIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, tapIntent, PendingIntent.FLAG_IMMUTABLE
        );

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_stat_kbs)
                .setColor(ContextCompat.getColor(this, R.color.kbs_logo_blue))
                .setContentTitle(title)
                .setContentText(message)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true);

        NotificationManagerCompat.from(this).notify((int) System.currentTimeMillis(), builder.build());
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID, "KBS Varsler", NotificationManager.IMPORTANCE_HIGH
            );
            getSystemService(NotificationManager.class).createNotificationChannel(channel);
        }
    }
}