package com.appticsreactnative;

import android.app.Activity;
import android.app.Application;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactMethod;
import com.appticsreactnative.NativeAppticsReactModuleSpec;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableMapKeySetIterator;
import com.facebook.react.bridge.ReadableNativeMap;
import com.facebook.react.bridge.ReadableType;
import com.facebook.react.module.annotations.ReactModule;
import com.zoho.apptics.analytics.AppticsAnalytics;
import com.zoho.apptics.analytics.AppticsEvents;
import com.zoho.apptics.analytics.AppticsScreenTracker;
import com.zoho.apptics.analytics.DefinedEvent;
import com.zoho.apptics.analytics.DefinedEventOperator;
import com.zoho.apptics.common.Apptics;
import com.zoho.apptics.common.AppticsSettings;
import com.zoho.apptics.common.AppticsTrackingState;
import com.zoho.apptics.common.AppticsUser;
import com.zoho.apptics.crash.AppticsCrashTracker;
import com.zoho.apptics.crash.AppticsNonFatals;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Method;

@ReactModule(name = AppticsReactModule.NAME)
public class AppticsReactModule extends NativeAppticsReactModuleSpec {
    public static final String NAME = "AppticsReactModule";

    public AppticsReactModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @ReactMethod
    public void initWithScreenTrackingStatus(boolean enableAutomaticScreenTracking) {
        Activity activity = getCurrentActivity();
        if (activity != null) {
            AppticsAnalytics.INSTANCE.setAutomaticActivityTrackingStatus(enableAutomaticScreenTracking);
            Apptics.INSTANCE.init(activity);
        } else {
            try {
                Application application = (Application) getReactApplicationContext().getApplicationContext();
                AppticsAnalytics.INSTANCE.setAutomaticActivityTrackingStatus(enableAutomaticScreenTracking);
                Apptics.INSTANCE.init(application);
            } catch (Throwable e) {
                Log.e("Apptics", "Initialization Error", e);
            }
        }
    }

    @ReactMethod
    public void init(boolean enableAutoScreenTracking) {
        initWithScreenTrackingStatus(enableAutoScreenTracking);
    }

    @ReactMethod
    public void flush() {
      Apptics.INSTANCE.flush();
    }

    @ReactMethod
    public void setCustomProperties(ReadableMap properties) {
      try {
        AppticsCrashTracker.INSTANCE.setCustomProperties(reactToJSON(properties));
      } catch (JSONException ignored) {}
    }

    @ReactMethod
    public void setCurrentUser(
      String userId,
      ReadableMap properties
    ) {
      if (userId != null && !userId.isEmpty()) {
        AppticsUser.AppticsUserProperty property = null;
        if (properties != null) {
            property = readableMapToUserProperties(properties);
        }
        AppticsUser.INSTANCE.setUser(userId, property);
      }
    }

    @ReactMethod
    public void setUserWithOrgId(
      String userId,
      String orgId,
      ReadableMap properties
    ) {
      if (userId != null && !userId.isEmpty() && orgId != null && !orgId.isEmpty()) {
        AppticsUser.INSTANCE.setUserWithOrgId(userId, orgId, properties != null ? readableMapToUserProperties(properties) : null);
      }
    }

    private AppticsUser.AppticsUserProperty readableMapToUserProperties(ReadableMap map) {
        ReadableMapKeySetIterator iterator = map.keySetIterator();
        AppticsUser.AppticsUserPropertyBuilder builder = new AppticsUser.AppticsUserPropertyBuilder();
        while (iterator.hasNextKey()) {
            String key = iterator.nextKey();
            ReadableType valueType = map.getType(key);
            switch (valueType) {
                case Boolean:
                     builder.addBooleanProperty(key, map.getBoolean(key));
                    break;
                case Number:
                    double value = map.getDouble(key);
                    if (key.equals("date_of_birth")) {
                        builder.setDateOfBirth(Math.round(value));
                    } else {
                        builder.addNumberProperty(key, value);
                    }
                    break;
                case String:
                     builder.addStringProperty(key, map.getString(key));
                    break;
                default:
                    break;
            }
        }
        return builder.build();
    }

    @ReactMethod
    public void isUserLoggedIn(Promise promise) {
        promise.resolve(AppticsUser.INSTANCE.getCurrentUser() != null);
    }

    @ReactMethod
    public void getTrackingStatus(Promise promise) {
        promise.resolve(AppticsSettings.INSTANCE.getTrackingStatus().getValue());
    }

    @ReactMethod
    public void setTrackingStatus(double status) {
      int statusInt = (int) status;
      for (AppticsTrackingState state: AppticsTrackingState.values()) {
        if (state.getValue() == statusInt) {
          AppticsSettings.INSTANCE.setTrackingStatus(state);
          return;
        }
      }
    }

    @ReactMethod
    public void openSettings() {
      Activity currentActivity = getCurrentActivity();
      if (currentActivity != null && !currentActivity.isFinishing()) {
        AppticsAnalytics.INSTANCE.openSettings(currentActivity);
      }
    }

    @ReactMethod
    public void showLastSessionCrashedPopup() {
      Activity currentActivity = getCurrentActivity();
      if (currentActivity != null && !currentActivity.isFinishing()) {
        AppticsCrashTracker.INSTANCE.showLastSessionCrashedPopup(currentActivity, true);
      }
    }

    @ReactMethod
    public void showPrivacyReviewPopup() {
      Activity currentActivity = getCurrentActivity();
      if (currentActivity != null && !currentActivity.isFinishing()) {
        AppticsAnalytics.showReviewTrackingSettingsPopup(currentActivity);
      }
    }

    @ReactMethod
    public void addEvent(String eventName, String groupName, ReadableMap properties) {
        if (eventName.toLowerCase().startsWith("ap_")) {
            DefinedEventOperator definedEvent = DefinedEvent.Companion.getDefinedEventOperator(eventName, groupName);
            if (definedEvent != null) {
                AppticsEvents.INSTANCE.addEvent(definedEvent);
            }
        } else {
            try {
                AppticsEvents.INSTANCE.addEvent(eventName, groupName, reactToJSON(properties));
            } catch (JSONException ignored) {}
        }
    }

    @ReactMethod
    public void trackScreenAttached(String screenName) {
      AppticsScreenTracker.INSTANCE.startUniqueScreen(screenName);
    }

    @ReactMethod
    public void trackScreenDetached(String screenName) {
      AppticsScreenTracker.INSTANCE.endUniqueScreen(screenName);
    }

    @ReactMethod
    public void sendJSException(String issueName, String stacktrace, @Nullable String extraStack, @Nullable String uniqueId) {
       AppticsCrashTracker.INSTANCE.recordJsCrash(issueName, stacktrace);
    }

    @ReactMethod
    public void sendNonFatalJsException(String issueName, String stacktrace, @Nullable String extraStack, @Nullable String uniqueId) {
      AppticsNonFatals.INSTANCE.recordJsException(issueName, stacktrace);
    }

    // iOS-only stubs — required by the shared codegen spec
    @ReactMethod
    public void setCrashReportStatus(boolean status) {}

    @ReactMethod
    public void setPersonalInfoTrackingStatus(boolean status) {}

    @ReactMethod
    public void trackViewEnter(String name) {}

    @ReactMethod
    public void trackViewExit(String name) {}

    @ReactMethod
    public void activateCrashListener() {}


    public static JSONObject reactToJSON(ReadableMap value) throws JSONException {
        if (value == null) {
            return new JSONObject();
        }

        JSONObject properties = new JSONObject();
        ReadableMapKeySetIterator iterator = value.keySetIterator();

        while (iterator.hasNextKey()) {
            String key = iterator.nextKey();
            ReadableType valueType = value.getType(key);

            switch (valueType) {
                case Null:
                    properties.put(key, JSONObject.NULL);
                    break;
                case Boolean:
                    properties.put(key, value.getBoolean(key));
                    break;
                case Number:
                    double numberValue = value.getDouble(key);
                    if (!Double.isNaN(numberValue) && !Double.isInfinite(numberValue)) {
                        properties.put(key, numberValue);
                    } else {
                        properties.put(key, String.valueOf(numberValue));
                    }
                    break;
                case String:
                    properties.put(key, value.getString(key));
                    break;
                default:
                    throw new IllegalArgumentException("Unsupported readableMap");
            }
        }
        return properties;
    }
}
