//
//  IndusBitTest.m
//  IndusBitTest
//
//  Created by IndusBit Team
//  Copyright © 2023 IndusBit. All rights reserved.
//

#import "IndusBitTest.h"
#import "SnapmintEventEmitter.h"
#import "SnapmintCheckoutWrapper.h"

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


@implementation IndusBitTest

RCT_EXPORT_MODULE()

+ (BOOL)requiresMainQueueSetup {
    return YES;
}

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:@"IndusBitTest" 
                                            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(@"🚀 [IndusBitTest] open method called with options: %@", options);
    
    NSString *checkoutUrl = options[@"checkoutUrl"];
    
    if (!checkoutUrl || [checkoutUrl length] == 0) {
        NSLog(@"❌ [IndusBitTest] Checkout URL is required");
        [self onSnapmintPaymentError:400 
                          description:@"Checkout URL is required" 
                              andData:nil];
        return;
    }
    
    dispatch_sync(dispatch_get_main_queue(), ^{
        NSLog(@"✅ [IndusBitTest] Starting real Snapmint checkout with URL: %@", checkoutUrl);
        
        // Get root view controller (like Razorpay)
        id<UIApplicationDelegate> app = [[UIApplication sharedApplication] delegate];
        UIViewController *rootViewController = (UIViewController*)app.window.rootViewController;
        
        if (rootViewController.presentedViewController) {
            rootViewController = rootViewController.presentedViewController;
        }
        
        // Convert checkoutUrl to URL
        NSURL *url = [NSURL URLWithString:checkoutUrl];
        if (!url) {
            NSLog(@"❌ [IndusBitTest] Invalid URL format: %@", checkoutUrl);
            [self onSnapmintPaymentError:400 
                              description:@"Invalid checkout URL format" 
                                  andData:nil];
            return;
        }
        
        // Create real SnapmintSkipOtpCheckoutView following SDK documentation
        @try {
            NSLog(@"📱 [IndusBitTest] Creating real SnapmintSkipOtpCheckoutView with URL: %@", url);
            
            // Create the SwiftUI view wrapper for Objective-C bridge
            SnapmintCheckoutWrapper *wrapper = [[SnapmintCheckoutWrapper alloc] 
                initWithUrl:url 
                completion:^(NSDictionary * _Nullable result, NSString * _Nullable error) {
                    if (error) {
                        NSLog(@"❌ [IndusBitTest] Snapmint checkout failed: %@", error);
                        [self onSnapmintPaymentError:500 description:error andData:nil];
                    } else {
                        NSLog(@"✅ [IndusBitTest] Snapmint checkout succeeded: %@", result);
                        NSString *paymentId = result[@"paymentId"] ?: @"SNAPMINT_SUCCESS";
                        [self onSnapmintPaymentSuccess:paymentId andData:result];
                    }
                }];
            
            // Create UIHostingController with the SwiftUI view
            UIViewController *hostingController = [wrapper createHostingController];
            hostingController.modalPresentationStyle = UIModalPresentationFullScreen;
            
            // Present the checkout view
            [rootViewController presentViewController:hostingController animated:YES completion:^{
                NSLog(@"✅ [IndusBitTest] Snapmint checkout view presented successfully");
            }];
            
        } @catch (NSException *exception) {
            NSLog(@"💥 [IndusBitTest] Exception creating Snapmint view: %@", exception.reason);
            [self onSnapmintPaymentError:500 
                              description:exception.reason ?: @"Failed to create checkout view" 
                                  andData:nil];
        }
    });
}

// Delegate-style methods that forward to event emitter (like Razorpay)
- (void)onSnapmintPaymentSuccess:(NSString *)paymentId andData:(NSDictionary *)response {
    NSLog(@"✅ [IndusBitTest] Payment success - forwarding to SnapmintEventEmitter");
    [SnapmintEventEmitter onPaymentSuccess:paymentId andData:response];
}

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

@end
