package com.grouplinksdk;

import androidx.annotation.NonNull;
import android.content.Context;
import android.util.Log;
import android.net.Uri;
import android.app.NotificationManager;
import android.app.AlarmManager;
import android.content.Intent;
import android.provider.Settings;
import android.os.Build;

import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.module.annotations.ReactModule;
import android.os.Handler;
import android.os.Looper;

import com.grouplinknetwork.GroupLink;

// NativeGrouplinkSdkSpec is generated by Codegen from src/NativeGroupLinkSDK.ts.
// The exact class name is derived from build.gradle libraryName="GrouplinkSdk"
// → NativeGrouplinkSdkSpec in package com.grouplinksdk.
@ReactModule(name = GrouplinkSdkModule.NAME)
public class GrouplinkSdkModule extends NativeGrouplinkSdkSpec implements LifecycleEventListener {
    public static final String NAME = "RNGroupLinkSDK";
    private final ReactApplicationContext mReactApplicationContext;
    private boolean glInitDone = false;
    private String token = "";
    private boolean debbugable = false;

    public GrouplinkSdkModule(ReactApplicationContext reactContext) {
        super(reactContext);
        mReactApplicationContext = reactContext;
        reactContext.addLifecycleEventListener(this);
    }

    @Override
    @NonNull
    public String getName() {
        return NAME;
    }

    // -------------------------------------------------------------------------
    // Android-specific methods
    // -------------------------------------------------------------------------

    @Override
    @ReactMethod
    public void getUserIdAndroid(Promise promise) {
        Context context = mReactApplicationContext.getApplicationContext();
        try {
            String userId = GroupLink.getUserId(context);
            promise.resolve(userId);
        } catch (Exception e) {
            e.printStackTrace();
            promise.reject("not_registered", e.getMessage());
        }
    }

    @Override
    @ReactMethod
    public void startAndroid(String token, boolean debbugable) {
        this.token = token;
        this.debbugable = debbugable;
        initGrouplink();
    }

    @Override
    @ReactMethod
    public void setFirebaseToken(String token) {
        Context context = mReactApplicationContext.getApplicationContext();
        if (token.equalsIgnoreCase("")) {
            Log.e("GL_K01", "not initing");
            return;
        }
        try {
            GroupLink.setFirebaseToken(context, token);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    @ReactMethod
    public void requestFullIntentPermissionAndroid() {
        try {
            Context context = mReactApplicationContext.getApplicationContext();
            NotificationManager notificationManager = (NotificationManager) context.getSystemService(ReactApplicationContext.NOTIFICATION_SERVICE);
            if (Build.VERSION.SDK_INT >= 34) {
                if (!notificationManager.canUseFullScreenIntent()) {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_APP_USE_FULL_SCREEN_INTENT);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setData(Uri.fromParts("package", context.getPackageName(), null));
                    context.startActivity(intent);
                }
            }
        } catch (Exception e) {
            Log.e("FullIntent", "Failed to open settings: " + e.getMessage());
        }
    }

    @Override
    @ReactMethod
    public void setRemoteId(String remoteId) {
        try {
            Context context = mReactApplicationContext.getApplicationContext();
            GroupLink.setRemoteId(context, remoteId);
        } catch (Exception e) {
            Log.e("setRemoteId", "Failed: " + e.getMessage());
        }
    }

    @Override
    @ReactMethod
    public void setNotificationNameAndroid(String notificationName) {
        try {
            Context context = mReactApplicationContext.getApplicationContext();
            GroupLink.setNotificationName(context, notificationName);
        } catch (Exception e) {
            Log.e("setNotificationName", "Failed: " + e.getMessage());
        }
    }

    @Override
    @ReactMethod
    public void getNotificationNameAndroid(Promise promise) {
        try {
            Context context = mReactApplicationContext.getApplicationContext();
            promise.resolve(GroupLink.getNotificationName(context));
        } catch (Exception e) {
            Log.e("getNotificationName", "Failed: " + e.getMessage());
            promise.reject("error", e.getMessage());
        }
    }

    @Override
    @ReactMethod
    public void requestScheduleExactAlarm() {
        try {
            Context context = mReactApplicationContext.getApplicationContext();
            AlarmManager alarmManager = (AlarmManager) context.getSystemService(ReactApplicationContext.ALARM_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && !alarmManager.canScheduleExactAlarms()) {
                Intent intent = new Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setData(Uri.fromParts("package", context.getPackageName(), null));
                context.startActivity(intent);
            }
        } catch (Exception e) {
            Log.e("requestScheduleExactAlarm", "Failed: " + e.getMessage());
        }
    }

    // -------------------------------------------------------------------------
    // iOS-only methods — no-ops on Android
    // -------------------------------------------------------------------------

    @Override
    @ReactMethod
    public void getUserID(Promise promise) {
        promise.reject("unsupported", "getUserID is iOS only");
    }

    @Override
    @ReactMethod
    public void setDevicePushToken(String withPushToken) {
        // iOS only
    }

    @Override
    @ReactMethod
    public void startIOS(String withToken) {
        // iOS only
    }

    @Override
    @ReactMethod
    public void setRemoteIdIOS(String remoteId) {
        // iOS only
    }

    @Override
    @ReactMethod
    public void startBluetoothIOS() {
        // iOS only
    }

    @Override
    @ReactMethod
    public void checkBluetoothIOS() {
        // iOS only
    }

    @Override
    @ReactMethod
    public void startLocationIOS() {
        // iOS only
    }

    @Override
    @ReactMethod
    public void setNotificationNameIOS(String withNotificationName) {
        // iOS only
    }

    @Override
    @ReactMethod
    public void getNotificationNameIOS(Promise promise) {
        promise.reject("unsupported", "getNotificationNameIOS is iOS only");
    }

    // -------------------------------------------------------------------------
    // Lifecycle
    // -------------------------------------------------------------------------

    @Override
    public void onHostDestroy() {}

    @Override
    public void onHostPause() {}

    @Override
    public void onHostResume() {
        initGrouplink();
    }

    // -------------------------------------------------------------------------
    // Private helpers
    // -------------------------------------------------------------------------

    private void initGrouplink() {
        Context context = mReactApplicationContext.getApplicationContext();
        if (token.equalsIgnoreCase("")) {
            Log.e("GL_K01", "not initing — token is empty");
            return;
        }
        Log.d("AndroidGL", "init android with: " + token);
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(() -> GroupLink.register(context, token, debbugable));
    }
}
