package com.amz.genie.services

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Intent
import android.media.AudioAttributes
import android.os.Build
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.net.toUri
import com.amz.genie.R
import com.amz.genie.activities.MainActivity
import com.google.firebase.messaging.RemoteMessage
import com.google.firebase.messaging.FirebaseMessagingService
import androidx.core.app.TaskStackBuilder
import com.amz.genie.activities.GeneralDetailActivity
import com.amz.genie.activities.GeneralSubDetailActivity


class MyFirebaseMessagingService: FirebaseMessagingService() {
    override fun onNewToken(token: String) {
        super.onNewToken(token)
        Log.d("FCM", "Refreshed token: $token")
    }

    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        super.onMessageReceived(remoteMessage)

        val titleFromNotif = remoteMessage.notification?.title
        val bodyFromNotif  = remoteMessage.notification?.body

        val title = remoteMessage.data["title"] ?: titleFromNotif
        val body  = remoteMessage.data["body"]  ?: bodyFromNotif

        Log.d("FCM", "data=${remoteMessage.data} notifTitle=$titleFromNotif")

        if (!title.isNullOrBlank() || !body.isNullOrBlank() || remoteMessage.data.isNotEmpty()) {
            sendNotification(title, body, remoteMessage.data)
        }
    }

    private fun ensureChannels(notificationManager: NotificationManager) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return

        val soundUri = "android.resource://${packageName}/${R.raw.notification}".toUri()
        val attrs = AudioAttributes.Builder()
            .setUsage(AudioAttributes.USAGE_NOTIFICATION)
            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
            .build()

        // DEFAULT
        val defaultChannel = NotificationChannel(
            "genie_default_v1",
            "Genie - Umum",
            NotificationManager.IMPORTANCE_DEFAULT
        )

        // URGENT (lebih kenceng)
        val urgentChannel = NotificationChannel(
            "genie_urgent_v1",
            "Genie - Penting",
            NotificationManager.IMPORTANCE_HIGH
        ).apply {
            enableVibration(true)
            setSound(soundUri, attrs)
            // enableLights(true) // optional
        }

        notificationManager.createNotificationChannel(defaultChannel)
        notificationManager.createNotificationChannel(urgentChannel)
    }

    private fun buildClickPendingIntent(data: Map<String, String>, requestCode: Int): PendingIntent {
        val open = data["open"] ?: "main"               // main | inbox_detail | inbox_subdetail
        val dataJson = data["data"]                     // JSON InboxThreadItem
        val counterpart = data["counterpart"]           // untuk subdetail

        // 1) MainActivity dulu (biar masuk app dan stack rapi)
        val mainIntent = Intent(this, MainActivity::class.java).apply {
            addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
            // optional: kasih sinyal supaya Main fokus ke inbox tab
            putExtra("open_tab", "inbox")
        }

        val stack = TaskStackBuilder.create(this)
        stack.addNextIntent(mainIntent)

        val aksiId = data["aksi_id"] ?: data["id_aksi"]   // support dua key
        val cp = data["counterpart"] ?: data["kode_pembuat"]
        val tentangId = data["tentang_id"] ?: data["id_tentang"]

        if (open == "inbox_subdetail") {
            // Kalau ada JSON lama, tetap support
            if (!dataJson.isNullOrBlank()) {
                val detailIntent = Intent(this, GeneralDetailActivity::class.java).apply {
                    putExtra("data", dataJson)
                }
                stack.addNextIntent(detailIntent)

                val subIntent = Intent(this, GeneralSubDetailActivity::class.java).apply {
                    putExtra("data", dataJson)
                    if (!counterpart.isNullOrBlank()) putExtra("counterpart", counterpart)
                }
                stack.addNextIntent(subIntent)
            } else if (!aksiId.isNullOrBlank() && !cp.isNullOrBlank()) {
                // ✅ Mode baru: buka thread pakai cp + aksi_id (tanpa JSON)
                val subIntent = Intent(this, GeneralSubDetailActivity::class.java).apply {
                    putExtra("aksi_id", aksiId)
                    putExtra("counterpart_kode", cp)
                    if (!tentangId.isNullOrBlank()) putExtra("tentang_id", tentangId)
                // optional: putExtra("tipe", data["tipe"])
                }
                stack.addNextIntent(subIntent)
            }
        }

        return stack.getPendingIntent(
            requestCode,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )!!
    }

    private fun sendNotification(
        title: String?,
        message: String?,
        data: Map<String, String>
    ) {
        val notificationManager =
            getSystemService(NOTIFICATION_SERVICE) as NotificationManager

        ensureChannels(notificationManager)

        val isUrgent = data["is_urgent"] == "yes"
        val channelId = if (isUrgent) "genie_urgent_v1" else "genie_default_v1"

        val soundUri = "android.resource://${packageName}/${R.raw.notification}".toUri()

        // Intent ketika notif diklik
        val notificationId = (System.currentTimeMillis() % Int.MAX_VALUE).toInt()
        val pendingIntent = buildClickPendingIntent(data, notificationId)

        val builder = NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.drawable.logo_normal)
            .setContentTitle(title ?: "Genie")
            .setContentText(message ?: "Ada notifikasi masuk")
            .setStyle(NotificationCompat.BigTextStyle().bigText(message ?: "Ada notifikasi masuk"))
            .setAutoCancel(true)
            .setContentIntent(pendingIntent) // ✅ INI KUNCI: biar klik ada aksi
            .setPriority(
                if (isUrgent) NotificationCompat.PRIORITY_HIGH
                else NotificationCompat.PRIORITY_DEFAULT
            )

        // Android < 8 (Oreo) perlu set sound langsung
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            builder.setSound(soundUri)
        }

        notificationManager.notify(notificationId, builder.build())
    }
}