package com.kbs.kbsintranett;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import retrofit2.Response;

public class NotificationWorker extends Worker {
    private static final String TAG = "NotificationWorker";
    private static final String PREFS_NAME = "kbs_alarm_history";

    public NotificationWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public Result doWork() {
        try {
            Response<List<CalendarEvent>> response = RetrofitClient.getApiService().getCalendarEvents().execute();
            if (response.isSuccessful() && response.body() != null) {
                scheduleAlarms(response.body());
                return Result.success();
            } else {
                if (response.code() >= 400 && response.code() < 500) return Result.failure();
                return Result.retry();
            }
        } catch (IOException e) {
            return Result.retry();
        }
    }

    private void scheduleAlarms(List<CalendarEvent> events) {
        Context context = getApplicationContext();
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && !alarmManager.canScheduleExactAlarms()) return;

        long now = System.currentTimeMillis();
        SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault());

        long catchUpWindow = now - (30 * 60 * 1000L);
        long futureWindow = now + (30 * 24 * 60 * 60 * 1000L); // 30 dager frem

        for (CalendarEvent event : events) {
            try {
                if (event.getRawDate() == null || event.getRawDate().length() == 10) continue;

                Date eventDate = null;
                if (event.getRawDate().contains("T")) {
                    String raw = event.getRawDate();
                    if (raw.length() > 19) raw = raw.substring(0, 19);
                    eventDate = isoFormat.parse(raw);
                }
                if (eventDate == null) continue;

                // Loop gjennom alle varsler for denne hendelsen
                for (int minutesBefore : event.getReminders()) {
                    if (minutesBefore < 0) continue; // 0 betyr nå "ved start", negative ignoreres

                    long triggerTime = eventDate.getTime() - (minutesBefore * 60 * 1000L);

                    // Unik nøkkel for denne alarmen: EventID + Tidspunkt
                    String alarmKey = "alarm_" + event.getId() + "_" + triggerTime;

                    // Sjekk om vi allerede har fyrt denne alarmen
                    if (prefs.getBoolean(alarmKey, false)) {
                        continue; // Allerede håndtert
                    }

                    if (triggerTime > catchUpWindow && triggerTime < futureWindow) {
                        if (triggerTime < now) {
                            triggerTime = now + 1000; // Catch-up
                        }

                        int alarmId = alarmKey.hashCode();
                        Intent intent = new Intent(context, AlarmReceiver.class);
                        intent.putExtra("TITLE", event.getTitle());
                        String timeStr = new SimpleDateFormat("HH:mm", Locale.getDefault()).format(eventDate);
                        intent.putExtra("MESSAGE", "Starter kl " + timeStr);
                        intent.putExtra("ID", alarmId);

                        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                                context, alarmId, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
                        );

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
                        } else {
                            alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
                        }

                        // Marker som satt
                        prefs.edit().putBoolean(alarmKey, true).apply();
                        Log.i(TAG, "Satt alarm: " + event.getTitle() + " (" + minutesBefore + "m før)");
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "Feil", e);
            }
        }

        // Rensk opp gamle nøkler (valgfritt, for å spare plass over tid)
    }
}