#import "GrovsWrapper.h"
#if __has_include(<react_native_grovs_wrapper/react_native_grovs_wrapper-Swift.h>)
#import <react_native_grovs_wrapper/react_native_grovs_wrapper-Swift.h>
#elif __has_include("react_native_grovs_wrapper-Swift.h")
#import "react_native_grovs_wrapper-Swift.h"
#else
// Fall back if neither header is found
#warning "Swift bridging header not found"
#endif

#ifdef RCT_NEW_ARCH_ENABLED

@implementation GrovsWrapper
RCT_EXPORT_MODULE()

+ (void)initialize {
  dispatch_async(dispatch_get_main_queue(), ^{
    GrovsWrapperSwift *wrapper = GrovsWrapperSwift.shared;
  });
}

- (instancetype)init {
  //self = [super init];
  if (self) {
    GrovsWrapperSwift.shared.didReceiveDeeplink = ^(NSDictionary<NSString *,id> * _Nonnull payload) {
      //[self emitOnDeeplinkReceived:payload];
      [self sendEventWithName:@"onGrovsDeeplinkReceived" body:payload];
    };
  }
  return self;
}

- (NSArray<NSString *> *)supportedEvents {
  return @[@"onGrovsDeeplinkReceived"];
}

- (void)addListener:(NSString *)eventName {
  [super addListener:eventName];
  
}

- (void)markReadyToHandleDeeplinks {
  dispatch_async(dispatch_get_main_queue(), ^{
    GrovsWrapperSwift.shared.bridgeLoaded = YES;
  });
}

- (void)removeListeners:(double)count {
  [super removeListeners:count];
}

- (void)setIdentifier:(NSString *)identifier {
  [GrovsWrapperSwift.shared setIdentifier:identifier];
}

- (void)setPushToken:(NSString *)pushToken {
  [GrovsWrapperSwift.shared setPushToken:pushToken];
}

- (void)setAttributes:(NSDictionary *)attributes {
  [GrovsWrapperSwift.shared setAttributes:attributes];
}

- (void)setSDK:(BOOL)enabled {
  [GrovsWrapperSwift.shared setSDK:enabled];
}

- (void)setDebug:(NSString *)level {
  [GrovsWrapperSwift.shared setDebug:level];
}

- (void)generateLink:(NSString *)title
            subtitle:(NSString *)subtitle
            imageURL:(NSString *)imageURL
                data:(NSDictionary *)data
                tags:(NSArray *)tags
     customRedirects:(JS::NativeGrovsWrapper::CustomRedirects &)customRedirects
         showPreviewIos:(NSNumber *)showPreviewIos
      showPreviewAndroid:(NSNumber *)showPreviewAndroid
            tracking:(JS::NativeGrovsWrapper::Tracking &)tracking
             resolve:(RCTPromiseResolveBlock)resolve
              reject:(RCTPromiseRejectBlock)reject {
  
  NSMutableDictionary *redirects = nil;
  
  // Check if customRedirects is not null before accessing its properties
  if (&customRedirects != nullptr) {
    NSMutableDictionary *androidDict = [NSMutableDictionary dictionary];
    JS::NativeGrovsWrapper::CustomLinkRedirect android = customRedirects.android();
    if (&android != nullptr) {
      if (android.link()) {
        androidDict[@"link"] = android.link();
      }
      androidDict[@"open_if_app_installed"] = @(android.open_if_app_installed());
    }
    
    NSMutableDictionary *iosDict = [NSMutableDictionary dictionary];
    JS::NativeGrovsWrapper::CustomLinkRedirect ios = customRedirects.ios();
    if (&ios != nullptr) {
      if (ios.link()) {
        iosDict[@"link"] = ios.link();
      }
      iosDict[@"open_if_app_installed"] = @(ios.open_if_app_installed());
    }
    
    NSMutableDictionary *desktopDict = [NSMutableDictionary dictionary];
    JS::NativeGrovsWrapper::CustomLinkRedirect desktop = customRedirects.desktop();
    if (&desktop != nullptr) {
      desktopDict[@"link"] = desktop.link();
    }
    desktopDict[@"open_if_app_installed"] = @(desktop.open_if_app_installed());
    
    redirects = [@{
      @"android": androidDict,
      @"ios": iosDict,
      @"desktop": desktopDict
    } mutableCopy];
  }

  NSMutableDictionary *nativeTracking = nil;
  
  // Check if tracking is not null before accessing its properties
  if (&tracking != nullptr) {
    nativeTracking = [NSMutableDictionary dictionary];
    
    if (tracking.utm_campaign()) {
      nativeTracking[@"utm_campaign"] = tracking.utm_campaign();
    }
    if (tracking.utm_source()) {
      nativeTracking[@"utm_source"] = tracking.utm_source();
    }
    if (tracking.utm_medium()) {
      nativeTracking[@"utm_medium"] = tracking.utm_medium();
    }
  }
  
  [GrovsWrapperSwift.shared generateLinkWithTitle:title
                                         subtitle:subtitle
                                         imageURL:imageURL
                                             data:data
                                             tags:tags
                                  customRedirects:redirects
                                      showPreviewIos:showPreviewIos
                               showPreviewAndroid:showPreviewAndroid
                                         tracking:nativeTracking
                                       completion:^(NSURL * _Nullable link) {
    if (link.absoluteString != nil) {
      resolve(link.absoluteString);
    } else {
      reject(@"100", @"Failed to generate the link!", nil);
    }
  }];
}

- (void)displayMessages:(RCTPromiseResolveBlock)resolve
                 reject:(RCTPromiseRejectBlock)reject {
  [GrovsWrapperSwift.shared displayMessagesViewControllerWithCompletion:^{
    resolve(nil);
  }];
}

- (void)numberOfUnreadMessages:(RCTPromiseResolveBlock)resolve
                        reject:(RCTPromiseRejectBlock)reject {
  [GrovsWrapperSwift.shared numberOfUnreadMessagesWithCompletion:^(NSInteger value) {
    if (value < 0) {
      reject(@"200", @"Failed to get number of messages", nil);
    } else {
      resolve(@(value));
    }
  }];
}

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

@end

#else

@implementation GrovsWrapper {
  bool hasListeners;
}

RCT_EXPORT_MODULE()

+ (void)initialize {
  dispatch_async(dispatch_get_main_queue(), ^{
    GrovsWrapperSwift *wrapper = GrovsWrapperSwift.shared;
  });
}

+ (BOOL)requiresMainQueueSetup {
  return YES;
}

- (instancetype)init
{
  self = [super init];
  if (self) {
    GrovsWrapperSwift.shared.didReceiveDeeplink = ^(NSDictionary<NSString *,id> * _Nonnull payload) {
      [self sendEventWithName:@"onGrovsDeeplinkReceived" body:payload];
    };
  }
  return self;
}

// Support for event emission
- (NSArray<NSString *> *)supportedEvents {
  return @[@"onGrovsDeeplinkReceived"];
}

- (void)startObserving {
  hasListeners = YES;
}

- (void)stopObserving {
  hasListeners = NO;
}

RCT_EXPORT_METHOD(setIdentifier:(NSString *)identifier) {
  [GrovsWrapperSwift.shared setIdentifier:identifier];
}

RCT_EXPORT_METHOD(setPushToken:(NSString *)pushToken) {
  [GrovsWrapperSwift.shared setPushToken:pushToken];
}

RCT_EXPORT_METHOD(setAttributes:(NSDictionary *)attributes) {
  [GrovsWrapperSwift.shared setAttributes:attributes];
}

RCT_EXPORT_METHOD(setSDK:(BOOL)enabled) {
  [GrovsWrapperSwift.shared setSDK:enabled];
}

RCT_EXPORT_METHOD(setDebug:(NSString *)level) {
  [GrovsWrapperSwift.shared setDebug:level];
}

RCT_EXPORT_METHOD(displayMessages:(RCTPromiseResolveBlock)resolve
                  reject:(RCTPromiseRejectBlock)reject) {
  [GrovsWrapperSwift.shared displayMessagesViewControllerWithCompletion:^{
    resolve(nil);
  }];
}

RCT_EXPORT_METHOD(numberOfUnreadMessages:(RCTPromiseResolveBlock)resolve
                  reject:(RCTPromiseRejectBlock)reject) {
  [GrovsWrapperSwift.shared numberOfUnreadMessagesWithCompletion:^(NSInteger value) {
    if (value < 0) {
      reject(@"200", @"Failed to get number of messages", nil);
    } else {
      resolve(@(value));
    }
  }];
}

RCT_EXPORT_METHOD(generateLink:(NSString *)title
                  subtitle:(NSString *)subtitle
                  imageURL:(NSString *)imageURL
                  data:(NSDictionary *)data
                  tags:(NSArray *)tags
                  customRedirects:(NSDictionary *)customRedirects
                  showPreviewIos:(nonnull NSNumber *)showPreviewIos
                  showPreviewAndroid:(nonnull NSNumber *)showPreviewAndroid
                  tracking:(NSDictionary *)tracking
                  resolve:(RCTPromiseResolveBlock)resolve
                  reject:(RCTPromiseRejectBlock)reject) {
  //  NSDictionary * redirects = @{@"android": @{@"link": customRedirects.android().link(),
  //                                             @"open_if_app_installed": @(customRedirects.android().open_if_app_installed())},
  //                               @"ios": @{@"link": customRedirects.ios().link(),
  //                                         @"open_if_app_installed": @(customRedirects.ios().open_if_app_installed())},
  //                               @"desktop": @{@"link": customRedirects.desktop().link(),
  //                                             @"open_if_app_installed": @(customRedirects.desktop().open_if_app_installed())},
  //  };
  [GrovsWrapperSwift.shared generateLinkWithTitle:title
                                         subtitle:subtitle
                                         imageURL:imageURL
                                             data:data
                                             tags:tags
                                  customRedirects:customRedirects
                                   showPreviewIos:showPreviewIos
                               showPreviewAndroid:showPreviewAndroid
                                         tracking:tracking
                                       completion:^(NSURL * _Nullable link) {
    if (link.absoluteString != nil) {
      resolve(link.absoluteString);
    } else {
      reject(@"100", @"Failed to generate the link!", nil);
    }
  }];
}

RCT_EXPORT_METHOD(markReadyToHandleDeeplinks) {
  dispatch_async(dispatch_get_main_queue(), ^{
    GrovsWrapperSwift.shared.bridgeLoaded = YES;
  });
}


@end

#endif
