//
//  APMessagingModule.m
//  apptics-react-native
//
//  Created by Saravanan S on 02/11/24.
//

#import "AppticsPushModule.h"
#import <AppticsMessaging/AppticsMessaging.h>

@implementation AppticsPushModule RCT_EXPORT_MODULE()


- (NSArray<NSString *> *)supportedEvents {
    return @[@"onNotificationActionClick", @"onNotificationClick", @"onMessageReceived"];
}


RCT_EXPORT_METHOD(notifyListenersActive){

}

RCT_EXPORT_METHOD(registerPushNotification){
    dispatch_async(dispatch_get_main_queue(), ^{
        UNUserNotificationCenter *notificationCenter = [UNUserNotificationCenter currentNotificationCenter];
        notificationCenter.delegate = self;
        [notificationCenter requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (error){
#if DEBUG
                NSLog(@"Error requestAuthorizationWithOptions %@", error);
#endif
            }
        }];
        UIApplication *application = [UIApplication sharedApplication];
        [application registerForRemoteNotifications];
    });
}

RCT_EXPORT_METHOD(startService){
    dispatch_async(dispatch_get_main_queue(), ^{
        [APMessaging startService];
    });
}

RCT_EXPORT_METHOD(setPresentationPreference:(NSString *)preference) {
  // Store in memory for next callback
  _presentationPreference = preference;
}

- (UNNotificationPresentationOptions)resolvePresentationOptionsFromJS {
  if ([self.presentationPreference isEqualToString:@"none"]) return UNNotificationPresentationOptionNone;
  if ([self.presentationPreference isEqualToString:@"banner"]) return UNNotificationPresentationOptionBanner;
  if ([self.presentationPreference isEqualToString:@"sound"]) return UNNotificationPresentationOptionSound;
  if ([self.presentationPreference isEqualToString:@"all"]) return UNNotificationPresentationOptionBanner | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionBadge;
  return UNNotificationPresentationOptionBanner;
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    NSDictionary *message=
    notification.request.content.userInfo;
    [self sendEventWithName:@"onMessageReceived" body:message];
    // Optional: allow JS to decide, wait briefly
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // Use a stored JS decision or fallback
        UNNotificationPresentationOptions options = [self resolvePresentationOptionsFromJS] ?: (UNNotificationPresentationOptionList | UNNotificationPresentationOptionBanner | UNNotificationPresentationOptionSound);
        completionHandler(options);
    });

}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
#if DEBUG
    NSLog(@"RN didReceiveRemoteNotification %@", userInfo);
#endif
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler{

    NSDictionary *message=
    response.notification.request.content.userInfo;

    if (message.count){

        NSString *addInfoString = [self findValueForKey:@"addInfo" inDictionary:message];
        if (addInfoString == nil)
            return;

        NSDictionary *addInfo = [self parseBodyString:addInfoString];
        if (addInfo == nil)
            return;

        NSNumber *pnID = addInfo[@"appticsPnID"];

        if (pnID) {

            NSString *actionIdentifier = [response actionIdentifier];
            if (![actionIdentifier isEqualToString:@"com.apple.UNNotificationDefaultActionIdentifier"]){
#if DEBUG
                NSLog(@"Action Identifier : %@ for Notification ID %@", actionIdentifier, pnID);
#endif
                NSArray *actionbuttons = [self findValueForKey:@"actionButton" inDictionary:addInfo];
                NSDictionary *actionbutton = [self getActionButtonById:actionIdentifier inArray:actionbuttons];
                NSString *actionId = actionbutton[@"action"];
                NSString *clickAction = actionbutton[@"clickAction"];

                [self sendEventWithName:@"onNotificationActionClick" body:@{@"actionId": (actionId) ? actionId : @"", @"clickAction": (clickAction) ? clickAction : @"", @"payload" : message}];

            }else{

                NSString *actionpath = addInfo[@"clickAction"];
                [self sendEventWithName:@"onNotificationClick" body:@{@"clickAction": (actionpath) ? actionpath : @"", @"payload" : message}];

            }

        }
    }

    completionHandler();
}


- (id)findValueForKey:(NSString *)key inDictionary:(NSDictionary *)dictionary {
    // Iterate over all keys in the dictionary
    for (NSString *currentKey in dictionary) {
        id value = dictionary[currentKey];

        // Check if the current key matches the key we're looking for
        if ([currentKey isEqualToString:key]) {
            return value;
        }

        // If the value is another dictionary, search recursively
        if ([value isKindOfClass:[NSDictionary class]]) {
            id foundValue = [self findValueForKey:key inDictionary:value];
            if (foundValue) {
                return foundValue;
            }
        }

        // If the value is an array, search recursively inside dictionaries in the array
        if ([value isKindOfClass:[NSArray class]]) {
            for (id item in value) {
                if ([item isKindOfClass:[NSDictionary class]]) {
                    id foundValue = [self findValueForKey:key inDictionary:item];
                    if (foundValue) {
                        return foundValue;
                    }
                }
            }
        }
    }

    // If the key is not found, return nil
    return nil;
}

- (NSDictionary *)getActionButtonById:(NSString *)buttonId inArray:(NSArray *)actionButtons {
    // Iterate through the array to find the button with the matching id
    for (NSDictionary *actionButton in actionButtons) {
        if ([actionButton[@"action"] isEqualToString:buttonId]) {
            return actionButton; // Return the action button dictionary if the id matches
        }
    }
    return nil; // Return nil if no matching id is found
}

-(NSDictionary*) parseBodyString : (NSString*) jsonString{
    // Convert the JSON string to NSData
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

    NSError *error = nil;
    // Convert NSData to NSDictionary
    NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];

    if (error) {
#if DEBUG
        NSLog(@"Error parsing push notification JSON payload: %@", error.localizedDescription);
#endif
        return nil;
    } else {
#if DEBUG
        NSLog(@"Push notification JSON payload %@", jsonObject);
#endif
        return jsonObject;
    }
}

#ifdef RCT_NEW_ARCH_ENABLED
- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:
    (const facebook::react::ObjCTurboModule::InitParams &)params
{
  return std::make_shared<facebook::react::NativeAppticsPushModuleSpecJSI>(params);
}
#endif

@end
