package com.openclaw.alfred.notifications

import android.Manifest
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 androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.openclaw.alfred.R
import com.openclaw.alfred.MainActivity

/**
 * Helper for managing Alfred notifications.
 */
object NotificationHelper {
    
    private const val CHANNEL_ID = "alfred_messages"
    private const val CHANNEL_NAME = "Alfred Messages"
    private const val CHANNEL_DESC = "Notifications from Alfred assistant"
    
    private const val ALARM_CHANNEL_ID = "alfred_alarms"
    private const val ALARM_CHANNEL_NAME = "Alfred Alarms"
    private const val ALARM_CHANNEL_DESC = "Time-sensitive alarm notifications from Alfred"
    
    private const val NOTIFICATION_ID_COUNTER_START = 1000
    private var notificationIdCounter = NOTIFICATION_ID_COUNTER_START
    
    /**
     * Create notification channel (required for Android 8.0+).
     * Call this once on app startup.
     */
    fun createNotificationChannel(context: Context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            
            // Regular messages channel
            val messagesChannel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT).apply {
                description = CHANNEL_DESC
                enableVibration(true)
                enableLights(true)
            }
            notificationManager.createNotificationChannel(messagesChannel)
            
            // High-priority alarm channel
            val alarmChannel = NotificationChannel(ALARM_CHANNEL_ID, ALARM_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH).apply {
                description = ALARM_CHANNEL_DESC
                enableVibration(true)
                enableLights(true)
                setBypassDnd(true) // Bypass Do Not Disturb
                lockscreenVisibility = android.app.Notification.VISIBILITY_PUBLIC
            }
            notificationManager.createNotificationChannel(alarmChannel)
        }
    }
    
    /**
     * Show a notification from Alfred.
     */
    fun showNotification(
        context: Context,
        title: String,
        message: String,
        autoCancel: Boolean = true,
        dismissAction: PendingIntent? = null
    ) {
        // Check notification permission (Android 13+)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ActivityCompat.checkSelfPermission(
                    context,
                    Manifest.permission.POST_NOTIFICATIONS
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                // Permission not granted, can't show notification
                return
            }
        }
        
        // Intent to open app when notification is tapped
        val intent = Intent(context, MainActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        }
        val pendingIntent = PendingIntent.getActivity(
            context,
            0,
            intent,
            PendingIntent.FLAG_IMMUTABLE
        )
        
        // Build notification
        val builder = NotificationCompat.Builder(context, CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentTitle(title)
            .setContentText(message)
            .setStyle(NotificationCompat.BigTextStyle().bigText(message))
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setContentIntent(pendingIntent)
            .setAutoCancel(autoCancel)
        
        // Add dismiss action if provided
        if (dismissAction != null) {
            builder.addAction(
                R.drawable.ic_launcher_foreground, // Icon
                "Dismiss", // Button text
                dismissAction // PendingIntent
            )
        }
        
        val notification = builder.build()
        
        // Show notification
        NotificationManagerCompat.from(context).notify(getNextNotificationId(), notification)
    }
    
    /**
     * Show a notification when Alfred finishes processing in background.
     */
    fun showBackgroundWorkComplete(context: Context, message: String) {
        showNotification(
            context = context,
            title = "AI Assistant",
            message = message,
            autoCancel = true
        )
    }
    
    /**
     * Show an alarm notification with full-screen intent and dismiss button.
     */
    fun showAlarmNotification(
        context: Context,
        alarmId: String,
        title: String,
        message: String,
        fullScreenIntent: PendingIntent,
        dismissAction: PendingIntent
    ) {
        // Check notification permission
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ActivityCompat.checkSelfPermission(
                    context,
                    Manifest.permission.POST_NOTIFICATIONS
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                return
            }
        }
        
        // Build alarm notification with full-screen intent using high-priority alarm channel
        val notification = NotificationCompat.Builder(context, ALARM_CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentTitle("⏰ ALARM: $title")
            .setContentText(message)
            .setStyle(NotificationCompat.BigTextStyle().bigText(message))
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setCategory(NotificationCompat.CATEGORY_ALARM)
            .setFullScreenIntent(fullScreenIntent, true) // Show full-screen on lock screen
            .setOngoing(true) // Can't swipe away
            .setAutoCancel(false) // Require dismissal
            .addAction(
                R.drawable.ic_launcher_foreground,
                "Dismiss",
                dismissAction
            )
            .build()
        
        // Show notification
        NotificationManagerCompat.from(context).notify(alarmId.hashCode(), notification)
    }
    
    /**
     * Cancel a specific alarm notification.
     */
    fun cancelAlarmNotification(context: Context, alarmId: String) {
        NotificationManagerCompat.from(context).cancel(alarmId.hashCode())
    }
    
    /**
     * Cancel all alarm notifications.
     */
    fun cancelAllAlarmNotifications(context: Context) {
        val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.activeNotifications.forEach { statusBarNotification ->
            if (statusBarNotification.notification.channelId == ALARM_CHANNEL_ID) {
                NotificationManagerCompat.from(context).cancel(statusBarNotification.id)
            }
        }
    }
    
    /**
     * Check if notification permission is granted (Android 13+).
     */
    fun hasNotificationPermission(context: Context): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            ActivityCompat.checkSelfPermission(
                context,
                Manifest.permission.POST_NOTIFICATIONS
            ) == PackageManager.PERMISSION_GRANTED
        } else {
            // No permission needed before Android 13
            true
        }
    }
    
    /**
     * Get next notification ID (auto-incrementing).
     */
    private fun getNextNotificationId(): Int {
        return notificationIdCounter++
    }
}
