package com.pedshub.scribe;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.webkit.PermissionRequest;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.getcapacitor.BridgeActivity;

public class MainActivity extends BridgeActivity {

    private static final int MIC_PERMISSION_CODE = 1001;
    private PermissionRequest pendingPermissionRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Request mic permission upfront
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{ Manifest.permission.RECORD_AUDIO }, MIC_PERMISSION_CODE);
        }

        // Setup WebView mic permission granting
        setupWebViewPermissions();

        // Register JS interface for foreground service control
        setupRecordingBridge();
    }

    // ── WebView Microphone Permission ──────────────────────────

    private void setupWebViewPermissions() {
        WebView webView = this.bridge.getWebView();
        final MainActivity activity = this;

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onPermissionRequest(final PermissionRequest request) {
                if (ContextCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO)
                        == PackageManager.PERMISSION_GRANTED) {
                    activity.runOnUiThread(() -> request.grant(request.getResources()));
                } else {
                    pendingPermissionRequest = request;
                    ActivityCompat.requestPermissions(activity,
                            new String[]{ Manifest.permission.RECORD_AUDIO }, MIC_PERMISSION_CODE);
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == MIC_PERMISSION_CODE && pendingPermissionRequest != null) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                final PermissionRequest req = pendingPermissionRequest;
                runOnUiThread(() -> req.grant(req.getResources()));
            } else {
                pendingPermissionRequest.deny();
            }
            pendingPermissionRequest = null;
        }
    }

    // ── Background Recording Service Bridge ───────────────────

    private void setupRecordingBridge() {
        WebView webView = this.bridge.getWebView();
        webView.addJavascriptInterface(new RecordingBridge(this), "NativeRecording");
    }

    public static class RecordingBridge {
        private final MainActivity activity;

        RecordingBridge(MainActivity activity) {
            this.activity = activity;
        }

        @android.webkit.JavascriptInterface
        public void startForegroundService() {
            Intent intent = new Intent(activity, AudioRecordingService.class);
            ContextCompat.startForegroundService(activity, intent);
        }

        @android.webkit.JavascriptInterface
        public void stopForegroundService() {
            Intent intent = new Intent(activity, AudioRecordingService.class);
            intent.setAction(AudioRecordingService.ACTION_STOP);
            activity.startService(intent);
        }
    }
}
