//
//  SnapmintRN.m
//  SnapmintRN
//
//  Created by Snapmint Team
//

#import "SnapmintRN.h"
#import "SnapmintEventEmitter.h"
#import <React/RCTBridge.h>
#import "SnapmintCheckoutWrapper.h"

// Import external Snapmint SDK (like Razorpay pattern)
#import <SnapmintMerchantSdk/SnapmintMerchantSdk.h>

@implementation SnapmintRN

RCT_EXPORT_MODULE(SnapmintRN)

+ (BOOL)requiresMainQueueSetup {
    return YES;
}

// Capture the RCTBridge so we can emit reliably to JS
- (void)setBridge:(RCTBridge *)bridge {
    _bridge = bridge;
    NSLog(@"🔗 [SnapmintRN] setBridge attached (%@)", bridge);
}

RCT_EXPORT_METHOD(multiply:(nonnull NSNumber *)a
                  b:(nonnull NSNumber *)b
                  resolver:(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject)
{
    @try {
        double result = [a doubleValue] * [b doubleValue];
        NSNumber *resultNum = @(result);
        resolve(resultNum);
    }
    @catch (NSException *exception) {
        NSError *error = [NSError errorWithDomain:@"SnapmintRN"
                                            code:500
                                        userInfo:@{
                                            @"message": exception.reason ?: @"Unknown error"
                                        }];
        reject(@"CALCULATION_ERROR",
               @"Error performing multiplication",
               error);
    }
}

// Fire-and-forget method like Razorpay (no resolver/rejecter)
RCT_EXPORT_METHOD(open:(NSDictionary *)options) {
    NSLog(@"🚀 [SnapmintRN] open method called with options: %@", options);
    
    NSString *checkoutUrl = options[@"checkoutUrl"];
    NSDictionary *header = options[@"header"];
    
    if (!checkoutUrl || [checkoutUrl length] == 0) {
        NSLog(@"❌ [SnapmintRN] Checkout URL is required");
        [self onSnapmintPaymentError:400 
                          description:@"Checkout URL is required" 
                              andData:nil];
        return;
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"✅ [SnapmintRN] Starting real Snapmint checkout with URL: %@", checkoutUrl);
        
        id<UIApplicationDelegate> app = [[UIApplication sharedApplication] delegate];
        UIViewController *rootViewController = (UIViewController*)app.window.rootViewController;
        
        if (rootViewController.presentedViewController) {
            rootViewController = rootViewController.presentedViewController;
        }
        
        NSURL *url = [NSURL URLWithString:checkoutUrl];
        if (!url) {
            NSLog(@"❌ [SnapmintRN] Invalid URL format: %@", checkoutUrl);
            [self onSnapmintPaymentError:400 
                              description:@"Invalid checkout URL format" 
                                  andData:nil];
            return;
        }
        
        @try {
            NSLog(@"📱 [SnapmintRN] Creating real SnapmintSkipOtpCheckoutView with URL: %@", url);
            
            if (header && [header isKindOfClass:[NSDictionary class]]) {
                self.currentCheckoutWrapper = [[SnapmintCheckoutWrapper alloc] initWithUrl:url header:header completion:^(NSDictionary * _Nullable result, NSString * _Nullable error) {
                    if (error) {
                        NSLog(@"❌ [SnapmintRN] Snapmint checkout failed: %@", error);
                        [self onSnapmintPaymentError:500 description:error andData:@{}];
                    } else {
                        NSLog(@"📦 [SnapmintRN] Received result: %@", result);
                        NSString *status = [[result valueForKey:@"status"] lowercaseString] ?: @"";
                        if ([status isEqualToString:@"success"] || [status isEqualToString:@"completed"] || [status isEqualToString:@"paid"]) {
                            NSString *paymentId = result[@"paymentId"] ?: @"SNAPMINT_SUCCESS";
                            [self onSnapmintPaymentSuccess:paymentId andData:result];
                        } else {
                            NSString *msg = result[@"responseMsg"] ?: result[@"message"] ?: @"Payment failed";
                            [self onSnapmintPaymentError:400 description:msg andData:result ?: @{}];
                        }
                    }
                    dispatch_async(dispatch_get_main_queue(), ^{
                        UIWindow *window = [UIApplication sharedApplication].delegate.window;
                        UIViewController *rootVC = window.rootViewController;
                        [rootVC dismissViewControllerAnimated:YES completion:^{
                            self.currentCheckoutWrapper = nil; // Release wrapper after dismiss
                        }];
                    });
                }];
            } else {
                self.currentCheckoutWrapper = [[SnapmintCheckoutWrapper alloc] initWithUrl:url completion:^(NSDictionary * _Nullable result, NSString * _Nullable error) {
                    if (error) {
                        NSLog(@"❌ [SnapmintRN] Snapmint checkout failed: %@", error);
                        [self onSnapmintPaymentError:500 description:error andData:@{}];
                    } else {
                        NSLog(@"📦 [SnapmintRN] Received result: %@", result);
                        NSString *status = [[result valueForKey:@"status"] lowercaseString] ?: @"";
                        if ([status isEqualToString:@"success"] || [status isEqualToString:@"completed"] || [status isEqualToString:@"paid"]) {
                            NSString *paymentId = result[@"paymentId"] ?: @"SNAPMINT_SUCCESS";
                            [self onSnapmintPaymentSuccess:paymentId andData:result];
                        } else {
                            NSString *msg = result[@"responseMsg"] ?: result[@"message"] ?: @"Payment failed";
                            [self onSnapmintPaymentError:400 description:msg andData:result ?: @{}];
                        }
                    }
                    dispatch_async(dispatch_get_main_queue(), ^{
                        UIWindow *window = [UIApplication sharedApplication].delegate.window;
                        UIViewController *rootVC = window.rootViewController;
                        [rootVC dismissViewControllerAnimated:YES completion:^{
                            self.currentCheckoutWrapper = nil; // Release wrapper after dismiss
                        }];
                    });
                }];
            }
            
            UIViewController *hostingController = [self.currentCheckoutWrapper createHostingController];
            hostingController.modalPresentationStyle = UIModalPresentationFullScreen;
            
            [rootViewController presentViewController:hostingController animated:YES completion:^{
                NSLog(@"✅ [SnapmintRN] Snapmint checkout view presented successfully");
            }];
            
        } @catch (NSException *exception) {
            NSLog(@"💥 [SnapmintRN] Exception creating Snapmint view: %@", exception.reason);
            [self onSnapmintPaymentError:500 
                              description:exception.reason ?: @"Failed to create checkout view" 
                                  andData:nil];
        }
    });
}

- (void)emitEventWithName:(NSString *)name body:(NSDictionary *)body {
    SnapmintEventEmitter *emitter = [self.bridge moduleForClass:[SnapmintEventEmitter class]];
    if (emitter) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [emitter sendEventWithName:name body:body];
        });
    } else {
        NSLog(@"⚠️ [SnapmintRN] Event emitter not available to send %@", name);
    }
}

-(void)onSnapmintPaymentSuccess:(NSString *)paymentId andData:(NSDictionary *)response {
    NSLog(@"✅ [SnapmintRN] Payment success - forwarding to SnapmintEventEmitter");
    [SnapmintEventEmitter onPaymentSuccess:paymentId andData:response ?: @{}];
}

-(void)onSnapmintPaymentError:(int)code description:(NSString *)description andData:(NSDictionary *)response {
    NSLog(@"❌ [SnapmintRN] Payment error - forwarding to SnapmintEventEmitter");
    [SnapmintEventEmitter onPaymentError:code description:description andData:response ?: @{}];
}

@end
