#import <React/RCTBridgeModule.h>
#import <QmsPluginSpec/QmsPluginSpec.h>
#import <QmsPluginFramework/QmsPluginFramework.h>

@interface QmsPlugin : NSObject <NativeQmsPluginSpec>
@end

@implementation QmsPlugin

RCT_EXPORT_MODULE()

RCT_EXPORT_METHOD(showPluginUI)
{
  [self showPluginUI];
}

- (instancetype)init {
  if (self = [super init]) {
    NSLog(@"[QmsPlugin] Native module initialized");
  }
  return self;
}

// Wraps the C function QmsPluginMultiply
- (NSNumber *)multiply:(double)a b:(double)b {
    NSLog(@"[QmsPlugin] multiply called with a=%f, b=%f", a, b);
    NSNumber *result = [QmsPluginFunc multiplyA:a withB:b];
    NSLog(@"[QmsPlugin] multiply result = %@", result);
    return result;
}

// Wraps the C function QmsPluginMakeViewController
- (void)showPluginUI {
  NSLog(@"[QmsPlugin] showPluginUI CALLED from JS");

  dispatch_async(dispatch_get_main_queue(), ^{
    UIViewController *vc = [QmsPluginUI makeViewController];
    NSLog(@"[QmsPlugin] created QmsPluginViewController: %@", vc);

    // Find topmost view controller
    UIWindow *keyWindow = nil;
    for (UIWindowScene *scene in UIApplication.sharedApplication.connectedScenes) {
      if (scene.activationState == UISceneActivationStateForegroundActive) {
        keyWindow = scene.windows.firstObject;
        if (keyWindow) break;
      }
    }

    if (keyWindow == nil) {
      NSLog(@"[QmsPlugin] ERROR: keyWindow is nil");
      return;
    } else {
      NSLog(@"[QmsPlugin] Found keyWindow: %@", keyWindow);
    }

    UIViewController *presentingVC = keyWindow.rootViewController;
    NSLog(@"[QmsPlugin] rootViewController = %@", presentingVC);

    while (presentingVC.presentedViewController) {
      presentingVC = presentingVC.presentedViewController;
    }

    if (presentingVC) {
      NSLog(@"[QmsPlugin] Presenting VC = %@", presentingVC);
      [presentingVC presentViewController:vc animated:YES completion:^{
        NSLog(@"[QmsPlugin] UI presented successfully");
      }];
    } else {
      NSLog(@"[QmsPlugin] ERROR: No presenting view controller");
    }
  });
}

// TurboModule boilerplate
- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:
    (const facebook::react::ObjCTurboModule::InitParams &)params
{
    return std::make_shared<facebook::react::NativeQmsPluginSpecJSI>(params);
}

@end
