package com.tomhempel.rbarometer.ui

import android.Manifest
import android.app.Activity
import android.content.pm.PackageManager
import android.os.Build
import android.view.LayoutInflater
import androidx.activity.result.ActivityResultLauncher
import androidx.core.content.ContextCompat
import com.tomhempel.rbarometer.R
import com.google.android.material.dialog.MaterialAlertDialogBuilder

/**
 * Shows a bilingual (DE + EN) explanation before the system notification permission dialog.
 */
object NotificationPermissionPrompter {
    private const val PREF = "app_settings"
    private const val KEY_RATIONALE_ACK = "notification_rationale_acknowledged"

    fun shouldShow(context: Activity): Boolean {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return false
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS)
            == PackageManager.PERMISSION_GRANTED
        ) {
            return false
        }
        return !context.getSharedPreferences(PREF, android.content.Context.MODE_PRIVATE)
            .getBoolean(KEY_RATIONALE_ACK, false)
    }

    fun showIfNeeded(
        activity: Activity,
        permissionLauncher: ActivityResultLauncher<String>,
        onDismissed: () -> Unit = {},
    ) {
        if (!shouldShow(activity)) {
            onDismissed()
            return
        }
        val view = LayoutInflater.from(activity).inflate(R.layout.dialog_notification_permission, null)
        MaterialAlertDialogBuilder(activity)
            .setView(view)
            .setCancelable(true)
            .setPositiveButton(activity.getString(R.string.notification_permission_continue)) { _, _ ->
                markAcknowledged(activity)
                permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
                onDismissed()
            }
            .setNegativeButton(activity.getString(R.string.notification_permission_later)) { _, _ ->
                onDismissed()
            }
            .setOnCancelListener { onDismissed() }
            .show()
    }

    private fun markAcknowledged(context: Activity) {
        context.getSharedPreferences(PREF, android.content.Context.MODE_PRIVATE).edit()
            .putBoolean(KEY_RATIONALE_ACK, true)
            .apply()
    }
}
