package com.recordatorios.app

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import java.util.Calendar

class ReminderReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        val action = intent.action
        val noteId = intent.getLongExtra(EXTRA_NOTE_ID, -1L)
        
        if (action == ACTION_SNOOZE || action == ACTION_COMPLETE) {
            handleNotificationAction(context, action, noteId)
            return
        }
        
        val noteTitle = intent.getStringExtra(EXTRA_NOTE_TITLE) ?: "Recordatorio"
        val noteContent = intent.getStringExtra(EXTRA_NOTE_CONTENT) ?: ""
        val photoPath = intent.getStringExtra(EXTRA_PHOTO_PATH) ?: ""

        if (noteId == -1L) return

        createNotificationChannel(context)

        val openIntent = Intent(context, MainActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        }

        val pendingIntent = PendingIntent.getActivity(
            context, noteId.toInt(), openIntent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )

        val snoozeIntent = Intent(context, ReminderReceiver::class.java).apply {
            setAction(ACTION_SNOOZE)
            putExtra(EXTRA_NOTE_ID, noteId)
            putExtra(EXTRA_NOTE_TITLE, noteTitle)
        }
        val snoozePendingIntent = PendingIntent.getBroadcast(
            context, (noteId + 1000).toInt(), snoozeIntent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )

        val completeIntent = Intent(context, ReminderReceiver::class.java).apply {
            setAction(ACTION_COMPLETE)
            putExtra(EXTRA_NOTE_ID, noteId)
            putExtra(EXTRA_NOTE_TITLE, noteTitle)
        }
        val completePendingIntent = PendingIntent.getBroadcast(
            context, (noteId + 2000).toInt(), completeIntent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )

        val notificationBuilder = NotificationCompat.Builder(context, CHANNEL_ID)
            .setSmallIcon(android.R.drawable.ic_dialog_info)
            .setContentTitle(noteTitle)
            .setContentText(noteContent.ifBlank { "Tienes un recordatorio pendiente" })
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .addAction(R.drawable.ic_clock, "Posponer 10 min", snoozePendingIntent)
            .addAction(R.drawable.ic_check, "Completar", completePendingIntent)

        if (photoPath.isNotBlank()) {
            val bitmap = BitmapFactory.decodeFile(photoPath)
            if (bitmap != null) {
                @Suppress("DEPRECATION")
                val bigPictureStyle = NotificationCompat.BigPictureStyle()
                    .bigPicture(bitmap)
                bigPictureStyle.bigLargeIcon(null as Bitmap?)
                notificationBuilder.setStyle(bigPictureStyle)
            }
        }

        try {
            NotificationManagerCompat.from(context).notify(noteId.toInt(), notificationBuilder.build())
        } catch (e: SecurityException) {
            // Permission not granted
        }

        // Schedule next occurrence if recurring
        val recurrenceStr = intent.getStringExtra(EXTRA_RECURRENCE) ?: RecurrenceType.NONE.name
        val recurrence = try { RecurrenceType.valueOf(recurrenceStr) } catch (e: Exception) { RecurrenceType.NONE }

        if (recurrence != RecurrenceType.NONE) {
            val originalTime = intent.getLongExtra(EXTRA_REMINDER_TIME, 0L)
            if (originalTime > 0) {
                val nextTime = calculateNextRecurrence(originalTime, recurrence)
                val notesManager = NotesManager.getInstance(context)
                val note = notesManager.getNote(noteId)
                if (note != null) {
                    val updatedNote = note.copy(reminderDate = nextTime)
                    notesManager.updateNote(updatedNote)
                    ReminderScheduler.scheduleReminder(context, updatedNote)
                }
            }
        }
    }

    private fun handleNotificationAction(context: Context, action: String, noteId: Long) {
        if (noteId == -1L) return
        
        val notesManager = NotesManager.getInstance(context)
        val note = notesManager.getNote(noteId) ?: return

        if (action == ACTION_SNOOZE) {
            val prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE)
            val snoozeMinutes = prefs.getInt("snooze_minutes", 10)
            val newTime = System.currentTimeMillis() + snoozeMinutes * 60 * 1000
            val updatedNote = note.copy(reminderDate = newTime)
            notesManager.updateNote(updatedNote)
            ReminderScheduler.scheduleReminder(context, updatedNote)
            
            NotificationManagerCompat.from(context).cancel(noteId.toInt())
        } else if (action == ACTION_COMPLETE) {
            if (note.recurrence != RecurrenceType.NONE) {
                val nextTime = calculateNextRecurrence(note.reminderDate ?: System.currentTimeMillis(), note.recurrence)
                val updatedNote = note.copy(reminderDate = nextTime)
                notesManager.updateNote(updatedNote)
                ReminderScheduler.scheduleReminder(context, updatedNote)
            } else {
                notesManager.toggleComplete(noteId)
            }
            NotificationManagerCompat.from(context).cancel(noteId.toInt())
        }
    }

    private fun calculateNextRecurrence(currentTime: Long, recurrence: RecurrenceType): Long {
        val cal = Calendar.getInstance().apply { timeInMillis = currentTime }
        return when (recurrence) {
            RecurrenceType.DAILY -> cal.apply { add(Calendar.DAY_OF_YEAR, 1) }.timeInMillis
            RecurrenceType.WEEKLY -> cal.apply { add(Calendar.WEEK_OF_YEAR, 1) }.timeInMillis
            RecurrenceType.MONTHLY -> cal.apply { add(Calendar.MONTH, 1) }.timeInMillis
            RecurrenceType.YEARLY -> cal.apply { add(Calendar.YEAR, 1) }.timeInMillis
            else -> currentTime
        }
    }

    private fun createNotificationChannel(context: Context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                context.getString(R.string.reminder_channel_name),
                NotificationManager.IMPORTANCE_HIGH
            ).apply {
                description = context.getString(R.string.reminder_channel_desc)
            }
            val notificationManager =
                context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }

    companion object {
        const val CHANNEL_ID = "recordatorios_channel"
        const val EXTRA_NOTE_ID = "note_id"
        const val EXTRA_NOTE_TITLE = "note_title"
        const val EXTRA_NOTE_CONTENT = "note_content"
        const val EXTRA_RECURRENCE = "recurrence"
        const val EXTRA_REMINDER_TIME = "reminder_time"
        const val EXTRA_PHOTO_PATH = "photo_path"
        const val ACTION_SNOOZE = "com.recordatorios.app.ACTION_SNOOZE"
        const val ACTION_COMPLETE = "com.recordatorios.app.ACTION_COMPLETE"
    }
}
