package be.harmonics.saas;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import java.util.Map;

/**
 * Firebase Messaging Service to handle push notifications
 * This ensures deep links work correctly when the app is in the background
 */
public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "HarmonicSaaS";
    private static final String CHANNEL_ID = "push_notifications";
    private static final String CHANNEL_NAME = "Push Notifications";

    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        Log.d(TAG, "Message received from: " + remoteMessage.getFrom());

        // Get notification data
        Map<String, String> data = remoteMessage.getData();
        String deepLink = data.get("deepLink");

        Log.d(TAG, "Deep link: " + deepLink);

        // Get notification content
        String title = "Notification";
        String body = "";

        if (remoteMessage.getNotification() != null) {
            title = remoteMessage.getNotification().getTitle() != null
                ? remoteMessage.getNotification().getTitle()
                : title;
            body = remoteMessage.getNotification().getBody() != null
                ? remoteMessage.getNotification().getBody()
                : "";
        }

        // Also check data payload for title/body (some implementations send it there)
        if (data.containsKey("title")) {
            title = data.get("title");
        }
        if (data.containsKey("body")) {
            body = data.get("body");
        }

        // Show notification with deep link
        showNotification(title, body, deepLink, data);
    }

    @Override
    public void onNewToken(@NonNull String token) {
        super.onNewToken(token);
        Log.d(TAG, "New FCM token: " + token);
        // Pusher Beams handles token registration automatically
    }

    private void showNotification(String title, String body, String deepLink, Map<String, String> data) {
        // Create notification channel for Android O+
        createNotificationChannel();

        // Create intent for notification click
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        // Pass deep link and all data to the intent
        if (deepLink != null && !deepLink.isEmpty()) {
            intent.putExtra("deepLink", deepLink);
        }
        for (Map.Entry<String, String> entry : data.entrySet()) {
            intent.putExtra(entry.getKey(), entry.getValue());
        }

        // Generate a unique request code using hashCode to avoid truncation issues
        // Using currentTimeMillis() directly causes problems when cast to int
        int requestCode = generateUniqueId();

        PendingIntent pendingIntent = PendingIntent.getActivity(
            this,
            requestCode,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
        );

        // Build notification
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(android.R.drawable.ic_dialog_info) // Use default icon, replace with app icon
            .setContentTitle(title)
            .setContentText(body)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setAutoCancel(true)
            .setContentIntent(pendingIntent);

        // Show notification
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        if (notificationManager != null) {
            // Use the same unique ID for the notification
            notificationManager.notify(requestCode, builder.build());
            Log.d(TAG, "Notification shown with deep link: " + deepLink);
        }
    }

    /**
     * Generate a unique ID for notifications and pending intents
     * Uses hashCode of current time string to avoid truncation issues with direct casting
     */
    private int generateUniqueId() {
        // Use hashCode of the timestamp string to get a safe int value
        // This avoids the truncation problem of casting long to int
        return Long.toString(System.currentTimeMillis()).hashCode();
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                CHANNEL_ID,
                CHANNEL_NAME,
                NotificationManager.IMPORTANCE_HIGH
            );
            channel.setDescription("Push notifications");

            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(channel);
            }
        }
    }
}
