package com.dewemoji.app.plugins;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;

import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;

import com.dewemoji.app.OverlayBubbleService;
import com.getcapacitor.JSObject;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;

@CapacitorPlugin(name = "DewemojiOverlay")
public class DewemojiOverlayPlugin extends Plugin {
    private static final String APP_STATE_KEY = "app_state_json";

    @PluginMethod
    public void isOverlayPermissionGranted(PluginCall call) {
        JSObject out = new JSObject();
        out.put("granted", canDrawOverlays());
        call.resolve(out);
    }

    @PluginMethod
    public void openOverlayPermissionSettings(PluginCall call) {
        try {
            Intent intent = new Intent(
                Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                Uri.parse("package:" + getContext().getPackageName())
            );
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            getContext().startActivity(intent);
            call.resolve();
        } catch (Exception ex) {
            call.reject("Failed to open overlay settings", ex);
        }
    }

    @PluginMethod
    public void areNotificationsEnabled(PluginCall call) {
        JSObject out = new JSObject();
        out.put("enabled", notificationsEnabled());
        call.resolve(out);
    }

    @PluginMethod
    public void openNotificationSettings(PluginCall call) {
        try {
            Intent intent = new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
            intent.putExtra(Settings.EXTRA_APP_PACKAGE, getContext().getPackageName());
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            getContext().startActivity(intent);
            call.resolve();
        } catch (Exception ex) {
            call.reject("Failed to open notification settings", ex);
        }
    }

    @PluginMethod
    public void isBubbleRunning(PluginCall call) {
        JSObject out = new JSObject();
        out.put("running", OverlayBubbleService.isRunning());
        call.resolve(out);
    }

    @PluginMethod
    public void startBubble(PluginCall call) {
        JSObject out = new JSObject();

        if (!canDrawOverlays()) {
            out.put("started", false);
            out.put("reason", "overlay_permission_required");
            call.resolve(out);
            return;
        }

        if (!notificationsEnabled()) {
            out.put("started", false);
            out.put("reason", "notifications_required");
            call.resolve(out);
            return;
        }

        try {
            Intent intent = new Intent(getContext(), OverlayBubbleService.class);
            intent.setAction(OverlayBubbleService.ACTION_START);
            ContextCompat.startForegroundService(getContext(), intent);
            out.put("started", true);
            call.resolve(out);
        } catch (Exception ex) {
            call.reject("Failed to start Dewemoji bubble", ex);
        }
    }

    @PluginMethod
    public void stopBubble(PluginCall call) {
        try {
            Intent intent = new Intent(getContext(), OverlayBubbleService.class);
            intent.setAction(OverlayBubbleService.ACTION_STOP);
            getContext().startService(intent);
            JSObject out = new JSObject();
            out.put("stopped", true);
            call.resolve(out);
        } catch (Exception ex) {
            call.reject("Failed to stop Dewemoji bubble", ex);
        }
    }

    @PluginMethod
    public void getAppState(PluginCall call) {
        JSObject out = new JSObject();
        try {
            SharedPreferences prefs = nativePrefs();
            String raw = prefs.getString(APP_STATE_KEY, "{}");
            JSObject state = (raw == null || raw.trim().isEmpty()) ? new JSObject() : new JSObject(raw);
            out.put("state", state);
            call.resolve(out);
        } catch (Exception ex) {
            call.reject("Failed to read app state", ex);
        }
    }

    @PluginMethod
    public void setAppState(PluginCall call) {
        try {
            JSObject incoming = call.getObject("state", new JSObject());
            if (incoming == null) {
                incoming = new JSObject();
            }
            nativePrefs().edit().putString(APP_STATE_KEY, incoming.toString()).apply();
            JSObject out = new JSObject();
            out.put("saved", true);
            call.resolve(out);
        } catch (Exception ex) {
            call.reject("Failed to save app state", ex);
        }
    }

    private SharedPreferences nativePrefs() {
        return getContext().getSharedPreferences(OverlayBubbleService.PREFS_NAME, Context.MODE_PRIVATE);
    }

    private boolean canDrawOverlays() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        return Settings.canDrawOverlays(getContext());
    }

    private boolean notificationsEnabled() {
        if (!NotificationManagerCompat.from(getContext()).areNotificationsEnabled()) {
            return false;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            return ContextCompat.checkSelfPermission(
                getContext(),
                Manifest.permission.POST_NOTIFICATIONS
            ) == PackageManager.PERMISSION_GRANTED;
        }

        return true;
    }
}
