package be.harmonics.saas;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.webkit.ConsoleMessage;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import com.getcapacitor.BridgeActivity;

public class MainActivity extends BridgeActivity {
    private static final String TAG = "HarmonicSaaS";
    private String pendingDeepLink = null;
    private String lastProcessedMessageId = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // Register Pusher Beams plugin
        registerPlugin(PusherBeamsPlugin.class);

        super.onCreate(savedInstanceState);

        // Enable WebView debugging for development
        WebView.setWebContentsDebuggingEnabled(true);

        Log.d(TAG, "MainActivity created");

        // Override WebChromeClient to use custom log tag for JavaScript console logs
        getBridge().getWebView().setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                String message = consoleMessage.message();
                String sourceId = consoleMessage.sourceId();
                int lineNumber = consoleMessage.lineNumber();

                String logMessage = String.format("[JS:%d] %s", lineNumber, message);

                switch (consoleMessage.messageLevel()) {
                    case ERROR:
                        Log.e(TAG, logMessage);
                        break;
                    case WARNING:
                        Log.w(TAG, logMessage);
                        break;
                    case DEBUG:
                        Log.d(TAG, logMessage);
                        break;
                    default:
                        Log.i(TAG, logMessage);
                        break;
                }
                return true; // We handled the message
            }
        });

        // Handle deep link from notification click
        handleNotificationIntent(getIntent());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent); // Update the intent
        // Handle deep link when app is already running
        handleNotificationIntent(intent);
    }

    private void handleNotificationIntent(Intent intent) {
        if (intent == null) {
            return;
        }

        Log.d(TAG, "handleNotificationIntent - action: " + intent.getAction());

        // Check intent extras
        Bundle extras = intent.getExtras();
        if (extras == null) {
            Log.d(TAG, "No extras in intent");
            return;
        }

        // Check if this is an FCM message and if we've already processed it
        String messageId = extras.getString("google.message_id");
        if (messageId != null) {
            if (messageId.equals(lastProcessedMessageId)) {
                Log.d(TAG, "Already processed message: " + messageId);
                return;
            }
            lastProcessedMessageId = messageId;
            Log.d(TAG, "Processing FCM message: " + messageId);
        }

        // Get deep link from notification data
        String deepLink = extras.getString("deepLink");
        Log.d(TAG, "Deep link from extras: " + deepLink);

        // Check intent data URI as fallback
        if (deepLink == null && intent.getData() != null) {
            deepLink = intent.getData().toString();
            Log.d(TAG, "Data URI deepLink: " + deepLink);
        }

        if (deepLink != null && !deepLink.isEmpty() && deepLink.startsWith("/")) {
            Log.d(TAG, "Processing deep link: " + deepLink);
            pendingDeepLink = deepLink;

            // Navigate to deep link after WebView is ready
            if (getBridge() != null && getBridge().getWebView() != null) {
                navigateToDeepLink(deepLink);
            }
        } else {
            Log.d(TAG, "No valid deep link found");
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "MainActivity started");
        // Navigate to pending deep link after app starts
        if (pendingDeepLink != null && getBridge() != null && getBridge().getWebView() != null) {
            navigateToDeepLink(pendingDeepLink);
            pendingDeepLink = null;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "MainActivity resumed");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG, "MainActivity paused");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "MainActivity stopped");
    }

    private void navigateToDeepLink(String deepLink) {
        Log.d(TAG, "Scheduling navigation to: " + deepLink);

        // Try to store immediately, and retry if WebView isn't ready
        tryStoreDeepLink(deepLink, 0);
    }

    private void tryStoreDeepLink(String deepLink, int attempt) {
        if (attempt >= 10) {
            Log.e(TAG, "Failed to store deep link after 10 attempts");
            return;
        }

        // Escape the deep link to prevent JavaScript injection
        String escapedDeepLink = escapeJavaScriptString(deepLink);

        // Store deep link in localStorage and verify it was stored
        String storeJs = "try { " +
            "localStorage.setItem('pendingDeepLink', '" + escapedDeepLink + "'); " +
            "console.log('[Android] Stored deep link:', localStorage.getItem('pendingDeepLink')); " +
            "'stored: ' + localStorage.getItem('pendingDeepLink'); " +
            "} catch(e) { 'error: ' + e.message; }";

        getBridge().getWebView().evaluateJavascript(storeJs, result -> {
            Log.d(TAG, "localStorage result (attempt " + attempt + "): " + result);

            // If it failed (access denied), retry after a delay
            if (result != null && result.contains("error")) {
                Log.d(TAG, "Retrying in 500ms...");
                getBridge().getWebView().postDelayed(() -> {
                    tryStoreDeepLink(deepLink, attempt + 1);
                }, 500);
            }
        });
    }

    /**
     * Escape a string for safe use in JavaScript string literals
     * Prevents JavaScript injection by escaping special characters
     */
    private String escapeJavaScriptString(String input) {
        if (input == null) {
            return "";
        }
        return input
            .replace("\\", "\\\\")  // Backslash must be first
            .replace("'", "\\'")    // Single quote
            .replace("\"", "\\\"")  // Double quote
            .replace("\n", "\\n")   // Newline
            .replace("\r", "\\r")   // Carriage return
            .replace("\t", "\\t")   // Tab
            .replace("\b", "\\b")   // Backspace
            .replace("\f", "\\f");  // Form feed
    }
}
