package com.devlab.app.util

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.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import com.devlab.app.MainActivity
import com.devlab.app.R
import com.devlab.app.data.model.AppNotification

object NotificationHelper {

    private const val CHANNEL_GENERAL = "notifications_general"
    private const val CHANNEL_ALERTS = "notifications_alerts"

    fun createChannels(context: Context) {
        val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        val general = NotificationChannel(
            CHANNEL_GENERAL, "Notifications",
            NotificationManager.IMPORTANCE_DEFAULT
        ).apply {
            description = "Server notifications and alerts"
        }

        val alerts = NotificationChannel(
            CHANNEL_ALERTS, "Alerts",
            NotificationManager.IMPORTANCE_HIGH
        ).apply {
            description = "Important alerts requiring attention"
        }

        manager.createNotificationChannel(general)
        manager.createNotificationChannel(alerts)
    }

    fun showNotification(context: Context, notification: AppNotification) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(
                    context, Manifest.permission.POST_NOTIFICATIONS
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                return
            }
        }

        val intent = Intent(context, MainActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
            putExtra("open_notification", notification.id)
        }

        val pendingIntent = PendingIntent.getActivity(
            context, notification.id, intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )

        val markReadIntent = Intent(context, NotificationActionReceiver::class.java).apply {
            action = "com.devlab.app.MARK_READ"
            putExtra("notification_id", notification.id)
        }
        val markReadPendingIntent = PendingIntent.getBroadcast(
            context, notification.id + 1000, markReadIntent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )

        val channel = when (notification.type) {
            "error" -> CHANNEL_ALERTS
            "warning" -> CHANNEL_ALERTS
            else -> CHANNEL_GENERAL
        }

        val icon = when (notification.type) {
            "success" -> android.R.drawable.ic_dialog_info
            "error" -> android.R.drawable.ic_dialog_alert
            "warning" -> android.R.drawable.ic_dialog_alert
            else -> android.R.drawable.ic_dialog_info
        }

        val built = NotificationCompat.Builder(context, channel)
            .setSmallIcon(icon)
            .setContentTitle(notification.title)
            .setContentText(notification.message)
            .setStyle(NotificationCompat.BigTextStyle().bigText(notification.message))
            .setPriority(
                when (notification.type) {
                    "error" -> NotificationCompat.PRIORITY_HIGH
                    "warning" -> NotificationCompat.PRIORITY_DEFAULT
                    else -> NotificationCompat.PRIORITY_DEFAULT
                }
            )
            .setContentIntent(pendingIntent)
            .addAction(
                android.R.drawable.ic_input_add,
                "Mark Read",
                markReadPendingIntent
            )
            .setAutoCancel(true)
            .setWhen(parseTime(notification.created_at))

        NotificationManagerCompat.from(context).notify(notification.id, built.build())
    }

    private fun parseTime(time: String?): Long {
        if (time == null) return System.currentTimeMillis()
        return try {
            java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.US).apply {
                timeZone = java.util.TimeZone.getTimeZone("UTC")
            }.parse(time)?.time ?: System.currentTimeMillis()
        } catch (_: Exception) {
            System.currentTimeMillis()
        }
    }
}
