package com.recordatorios.app

import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.content.edit

object ReminderScheduler {

    fun scheduleReminder(context: Context, note: Note) {
        val reminderTime = note.reminderDate ?: return

        val currentTime = System.currentTimeMillis()
        if (reminderTime < currentTime) return

        val prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE)
        val showImageInNotif = prefs.getBoolean("notif_show_image", true)

        val intent = Intent(context, ReminderReceiver::class.java).apply {
            putExtra(ReminderReceiver.EXTRA_NOTE_ID, note.id)
            putExtra(ReminderReceiver.EXTRA_NOTE_TITLE, note.title.ifBlank { "Recordatorio" })
            putExtra(ReminderReceiver.EXTRA_NOTE_CONTENT, note.content)
            putExtra(ReminderReceiver.EXTRA_RECURRENCE, note.recurrence.name)
            putExtra(ReminderReceiver.EXTRA_REMINDER_TIME, reminderTime)
            if (showImageInNotif) putExtra(ReminderReceiver.EXTRA_PHOTO_PATH, note.photoPath)
        }

        val pendingIntent = PendingIntent.getBroadcast(
            context, note.id.toInt(), intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )

        val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager

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

    fun cancelReminder(context: Context, note: Note) {
        val intent = Intent(context, ReminderReceiver::class.java)
        val pendingIntent = PendingIntent.getBroadcast(
            context, note.id.toInt(), intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        alarmManager.cancel(pendingIntent)
        pendingIntent.cancel()
    }
}
