//
//  RazorpayCheckout.m
//  RazorpayCheckout
//
//  Created by Abhinav Arora on 11/10/17.
//  Copyright © 2016 Razorpay. All rights reserved.
//

#import <WebKit/WebKit.h>

#import "RazorpayCustomui.h"
#import "RazorpayEventEmitterCustom.h"

#import <RazorpayCustom/RazorpayCustom-Swift.h>
@import RazorpayCore;

// Mirrors RazorpayApplePay.ApplePay; the pod is optional so it is never imported.
@protocol RazorpayApplePayFactory <NSObject>
+ (id<ApplePayPlugin>)pluginInstance;
@end

@interface RazorpayCustomui () <RazorpayPaymentCompletionProtocolWithData, WKNavigationDelegate, WKUIDelegate>{
    RazorpayCheckout *razorpay;
    id<ApplePayPlugin> applePayPlugin; // outlives close(), which nils `razorpay`
    UIViewController *parentVC;
    WKWebView *webview;
    UINavigationController *navController;
    UIBarButtonItem *cancelBtn;
    UIWindow *window;
}
@end

@implementation RazorpayCustomui

RCT_EXPORT_MODULE()

RCT_EXPORT_METHOD(getAppsWhichSupportUpi) {
    [RazorpayCheckout getAppsWhichSupportUpiWithHandler:^(NSArray<NSDictionary *> * supportedApps) {
        [RazorpayEventEmitterCustom upiApps:supportedApps];
    }];
}

RCT_EXPORT_METHOD(initRazorpay: (NSString *)key){
    dispatch_sync(dispatch_get_main_queue(), ^{
        if (applePayPlugin == nil) {
            applePayPlugin = [self loadApplePayPlugin];
        }
        razorpay = applePayPlugin
            ? [RazorpayCheckout initWithKey:key andDelegate:self withPaymentWebView:nil ApplePay:applePayPlugin]
            : [RazorpayCheckout initWithKey:key andDelegate:self withPaymentWebView:nil];
    });
}

RCT_EXPORT_METHOD(getCardsNetwork : (NSString *)cardNumber){
   NSString *cardNetwork =  [razorpay getCardNetworkFromCardNumber:cardNumber];
    NSDictionary *dict = @{@"data":cardNetwork};
   [RazorpayEventEmitterCustom cardNetwork:dict];
}

RCT_EXPORT_METHOD(getCardNetworkLength: (NSString *)cardNetwork){
    NSInteger length = (long)[razorpay getCardNetworkLengthOfNetwork:cardNetwork];
    NSNumber *lenNum = [NSNumber numberWithInteger:(long)length];
    NSDictionary *dict = @{@"data":lenNum};
    [RazorpayEventEmitterCustom cardNetworkLength:dict];
}

RCT_EXPORT_METHOD(isCredAppAvailable){
    NSString *credUrl = @"credpay%3A%2F%2F";
    UIApplication *application = [UIApplication sharedApplication];
    NSURL *URL = [NSURL URLWithString:credUrl];
    [application openURL:URL options:@{} completionHandler:^(BOOL status){
        NSDictionary *dict = @{@"data":@(status)};
        [RazorpayEventEmitterCustom credAppAvailable:dict];

    }];


}

// nil when the RazorpayApplePay pod is not linked.
- (id<ApplePayPlugin>)loadApplePayPlugin {
    Class<RazorpayApplePayFactory> factory = NSClassFromString(@"RazorpayApplePay.ApplePay");
    if (factory == Nil || ![factory respondsToSelector:@selector(pluginInstance)]) {
        return nil;
    }
    return [factory pluginInstance];
}

// Uses the plugin attached in initRazorpay. Never re-runs initWithKey here: RazorpayCheckout
// is a singleton and that would swap the web view under an in-flight payment.
RCT_EXPORT_METHOD(canMakePayment){
    if (applePayPlugin == nil) {
        NSLog(@"[react-native-customui] canMakePayment: the RazorpayApplePay plugin is "
              @"not installed, or initRazorpay has not been called yet.");
        [RazorpayEventEmitterCustom applePaySupported:@{@"data": @(NO)}];
        return;
    }

    [applePayPlugin canMakePaymentWithCompletion:^(BOOL canPay) {
        [RazorpayEventEmitterCustom applePaySupported:@{@"data": @(canPay)}];
    }];
}

 RCT_EXPORT_METHOD(getPaymentMethods){
        [razorpay getPaymentMethodsWithOptions: nil withSuccessCallback: ^(NSDictionary *methods){
                 [RazorpayEventEmitterCustom paymentMethods:methods];
             } andFailureCallback: ^(NSString *error){
                  [RazorpayEventEmitterCustom paymentMethodsError:error];
             }];
 }

RCT_EXPORT_METHOD(getRecommendedInstruments:(NSDictionary *)options){
    [razorpay getRecommendedInstrumentsWithOptions:options withSuccessCallback:^(NSDictionary *recommendedInstruments){
        [RazorpayEventEmitterCustom recommendedInstruments:recommendedInstruments];
    } andFailureCallback:^(NSString *error){
        NSDictionary *dict = @{@"error": error};
        [RazorpayEventEmitterCustom recommendedInstrumentsError:dict];
    }];
}

RCT_EXPORT_METHOD(getWalletLogoUrl:(NSString *)walletName){
    NSURL *url = [razorpay getWalletLogoWithHavingWalletName:walletName];
    NSDictionary *dict = @{@"data":url.absoluteString};

    [RazorpayEventEmitterCustom walletLogoUrl:dict];
}

RCT_EXPORT_METHOD(getSubscriptionAmount:(NSString *)subscriptionId){
    [razorpay getSubscriptionAmountWithHavingSubscriptionId:subscriptionId withSuccessCallback:^(UInt64 subAmount){
        NSDictionary *dict = @{@"data":@(subAmount)};
        [RazorpayEventEmitterCustom subscriptionAmount:dict];
    } andFailureCallback:^(NSString *error){
        NSDictionary *dict = @{@"error":error};
        [RazorpayEventEmitterCustom subscriptionAmount:dict];
    }];
}

RCT_EXPORT_METHOD(isValidCardNumber:(NSString *)cardNumber){
    BOOL isCardValid = [razorpay isCardValid:cardNumber];
    NSDictionary *dict = @{@"data":@(isCardValid)};

    [RazorpayEventEmitterCustom cardNumberValidity:dict];
}

RCT_EXPORT_METHOD(isValidVpa:(NSString *)vpaAddress){
    [razorpay isValidVpa:vpaAddress withSuccessCallback:^(NSDictionary *success){
        [RazorpayEventEmitterCustom validVpa:success];
    } withFailure:^(NSDictionary *failure){
        [RazorpayEventEmitterCustom validVpa:failure];
    }];
}

RCT_EXPORT_METHOD(getBankLogoUrl:(NSString *)bankName){
    NSURL *url = [razorpay getBankLogoWithHavingBankCode:bankName];
    NSDictionary *dict = @{@"data":url.absoluteString};
    [RazorpayEventEmitterCustom bankLogoUrl:dict];
}

RCT_EXPORT_METHOD(getSqWalletLogoUrl:(NSString *)walletName){
    NSURL *url = [razorpay getWalletSqLogoWithHavingWalletName:walletName];
    NSDictionary *dict = @{@"data":url.absoluteString};
    [RazorpayEventEmitterCustom sqWalletLogoUrl:dict];
}


// Same predicate RazorpayCheckout.authorize routes on: method == "card" && app.name == "apple_pay".
- (BOOL)isApplePayRequested:(NSDictionary *)options {
    id method = [options objectForKey:@"method"];
    id app = [options objectForKey:@"app"];
    if (![method isKindOfClass:[NSString class]] || ![method isEqualToString:@"card"] ||
        ![app isKindOfClass:[NSDictionary class]]) {
        return NO;
    }
    id name = [(NSDictionary *)app objectForKey:@"name"];
    return [name isKindOfClass:[NSString class]] && [name isEqualToString:@"apple_pay"];
}

// apple_pay needs the 4-arg initialiser; everything else keeps the original 3-arg call.
// nil when apple_pay is requested without the plugin pod, so open() fails fast.
- (RazorpayCheckout *)checkoutWithKey:(NSString *)keyID
                              webView:(WKWebView *)paymentWebView
                           forOptions:(NSDictionary *)options {
    if (![self isApplePayRequested:options]) {
        return [RazorpayCheckout initWithKey:keyID andDelegate:self withPaymentWebView:paymentWebView];
    }
    if (applePayPlugin == nil) {
        applePayPlugin = [self loadApplePayPlugin];
    }
    if (applePayPlugin == nil) {
        return nil;
    }
    return [RazorpayCheckout initWithKey:keyID
                             andDelegate:self
                      withPaymentWebView:paymentWebView
                                ApplePay:applePayPlugin];
}

RCT_EXPORT_METHOD(open : (NSDictionary *)options) {

    NSString *keyID = (NSString *)[options objectForKey:@"key_id"];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleRotation) name:UIDeviceOrientationDidChangeNotification object:nil];

    dispatch_sync(dispatch_get_main_queue(), ^{

        // Apple Pay: PassKit shows its own sheet, so build the web view but do not present the window.
        [self setupPaymentWindowPresenting:![self isApplePayRequested:options]];

        razorpay = [self checkoutWithKey:keyID webView:webview forOptions:options];

        if (razorpay == nil) {
            NSLog(@"[react-native-customui] apple_pay requested but the RazorpayApplePay "
                  @"plugin is not installed. Add the RazorpayApplePay pod to your Podfile "
                  @"and run `pod install`.");
            [self close];
            NSString *message = @"Apple Pay is not available: the RazorpayApplePay plugin is not installed.";
            NSMutableDictionary *payload = [@{@"error": @{@"code": @"DEVICE_NOT_SUPPORTED",
                                                          @"description": message}} mutableCopy];
            [RazorpayEventEmitterCustom onPaymentError:0 description:message andData:payload];
            return;
        }

        NSMutableDictionary * tempOptions = [[NSMutableDictionary alloc] initWithDictionary:options];
        [razorpay authorize:tempOptions];
    });
}

/* Payment window + webview shared by open() and the native OTP bank page. */
- (void)setupPaymentWindow {
    [self setupPaymentWindowPresenting:YES];
}

- (void)setupPaymentWindowPresenting:(BOOL)presentWindow {

    cancelBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(onTapCancel:)];
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    //Setting web view
    webview = [[WKWebView alloc] initWithFrame: parentVC.view.frame configuration:configuration];
    webview.UIDelegate = self;
    webview.opaque = NO;
    webview.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4];

    [self resizeView];

    //setting parent view controller
    parentVC = [UIViewController new];
    [parentVC.view addSubview:webview];

    if ([[parentVC navigationController] navigationBar] != nil) {
        navController = parentVC.navigationController;
    } else {
        navController = [[UINavigationController alloc] initWithRootViewController:parentVC];
    }

    parentVC.title = @"Authorize Payment";
    parentVC.navigationItem.leftBarButtonItem = cancelBtn;


    parentVC.view.autoresizingMask =
    (UIViewAutoresizingFlexibleLeftMargin |
     UIViewAutoresizingFlexibleRightMargin |
     UIViewAutoresizingFlexibleBottomMargin |
     UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleHeight |
     UIViewAutoresizingFlexibleWidth);

    webview.autoresizingMask =
    (UIViewAutoresizingFlexibleLeftMargin |
     UIViewAutoresizingFlexibleRightMargin |
     UIViewAutoresizingFlexibleBottomMargin |
     UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleHeight |
     UIViewAutoresizingFlexibleWidth);

    if (presentWindow) {
        window = [self makePaymentWindow];
        window.windowLevel = UIWindowLevelStatusBar;
        window.backgroundColor = [UIColor whiteColor];
        webview.backgroundColor = [UIColor whiteColor];
        // setRootViewController: must run before makeKeyAndVisible so the window is
        // never displayed empty.
        [window setRootViewController:navController];
        [window makeKeyAndVisible];

        if (!window.isKeyWindow) {
            // The payment UI is only visible once its window is key. Log a
            // diagnostic rather than failing silently so a scene that was not
            // ready when the payment started is visible in the logs.
            NSLog(@"[react-native-customui] payment window is not key after makeKeyAndVisible; the payment UI may not be visible.");
        }
    }
}

// Returns the scene the payment window should attach to. Prefers a
// foreground-active scene (and, among those, the one that already owns the key
// window), then a foreground-inactive scene, then any other connected window
// scene. Returns nil only when the app has no window scene at all (legacy
// AppDelegate-based apps, or iOS < 13).
- (UIWindowScene *)activeWindowScene {
    if (@available(iOS 13.0, *)) {
        UIWindowScene *foregroundActiveScene = nil;
        UIWindowScene *foregroundInactiveScene = nil;
        UIWindowScene *anyWindowScene = nil;

        for (UIScene *scene in [UIApplication sharedApplication].connectedScenes) {
            if (![scene isKindOfClass:[UIWindowScene class]]) {
                continue;
            }
            UIWindowScene *windowScene = (UIWindowScene *)scene;
            if (anyWindowScene == nil) {
                anyWindowScene = windowScene;
            }

            BOOL ownsKeyWindow = NO;
            for (UIWindow *sceneWindow in windowScene.windows) {
                if (sceneWindow.isKeyWindow) {
                    ownsKeyWindow = YES;
                    break;
                }
            }

            if (windowScene.activationState == UISceneActivationStateForegroundActive) {
                if (foregroundActiveScene == nil) {
                    foregroundActiveScene = windowScene;
                }
                if (ownsKeyWindow) {
                    return windowScene;
                }
            } else if (windowScene.activationState == UISceneActivationStateForegroundInactive &&
                       foregroundInactiveScene == nil) {
                foregroundInactiveScene = windowScene;
            }
        }

        if (foregroundActiveScene != nil) {
            return foregroundActiveScene;
        }
        if (foregroundInactiveScene != nil) {
            return foregroundInactiveScene;
        }
        return anyWindowScene;
    }
    return nil;
}

// Builds the payment window, attaching it to a UIWindowScene when the host app
// adopts the scene lifecycle. A UIWindow created with initWithFrame: is never
// attached to a scene, so on scene-based apps it never becomes key and the
// payment UI stays invisible. initWithFrame: is only used when the app has no
// window scene at all, which keeps legacy AppDelegate-based apps working.
- (UIWindow *)makePaymentWindow {
    UIWindowScene *windowScene = [self activeWindowScene];
    if (windowScene != nil) {
        return [[UIWindow alloc] initWithWindowScene:windowScene];
    }
    return [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
}


RCT_EXPORT_METHOD(getCardsFlow : (NSDictionary *)options) {
    dispatch_sync(dispatch_get_main_queue(), ^{
        NSMutableDictionary *tempOptions = [[NSMutableDictionary alloc] initWithDictionary:options];
        [tempOptions removeObjectForKey:@"key_id"];
        [razorpay getCardFlows:tempOptions withCallback:^(BOOL isNativeOtpEnabled) {
            [RazorpayEventEmitterCustom nativeOtpEligible:@{@"data" : @(isNativeOtpEnabled)}];
        }];
    });
}

RCT_EXPORT_METHOD(getCardOtpData) {
    dispatch_sync(dispatch_get_main_queue(), ^{
        [razorpay getCardOtpDataWithResponse:^(BOOL otpGenerated) {
            [RazorpayEventEmitterCustom nativeOtpGenerated:@{@"data" : @(otpGenerated)}];
        }];
    });
}

RCT_EXPORT_METHOD(submitOtp : (NSString *)otp) {
    dispatch_sync(dispatch_get_main_queue(), ^{
        [razorpay submitOtpWithOtp:otp andFailureCallback:^(NSString *error) {
            [RazorpayEventEmitterCustom nativeOtpSubmitError:@{@"description" : error ?: @""}];
        }];
    });
}

RCT_EXPORT_METHOD(resendOtp) {
    dispatch_sync(dispatch_get_main_queue(), ^{
        [razorpay resendOtpWithResponse:^(BOOL otpResent) {
            [RazorpayEventEmitterCustom nativeOtpResent:@{@"data" : @(otpResent)}];
        }];
    });
}

RCT_EXPORT_METHOD(redirectToBankPage) {
    // Only the bank page needs a webview — create it and attach to the existing instance.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleRotation) name:UIDeviceOrientationDidChangeNotification object:nil];

    dispatch_sync(dispatch_get_main_queue(), ^{
        [self setupPaymentWindow];
        [razorpay setWebView:webview error:nil];
        [razorpay redirectToBankPage];
    });
}

// OTP Assist listener mode is Android-only (iOS cannot read SMS) — no-op stubs
RCT_EXPORT_METHOD(startOtpAssistListener) {}
RCT_EXPORT_METHOD(stopOtpAssistListener) {}

-(void)onTapCancel: (id) sender{
    [razorpay userCancelledPayment];
    [RazorpayEventEmitterCustom onPaymentError:1 description:@"User Cancelled Payment" andData:[NSMutableDictionary dictionary]];
    [razorpay close];
    [self close];
}

- (void)onPaymentSuccess:(nonnull NSString *)payment_id
                 andData:(NSDictionary *)response {
    if (response == nil){
        [RazorpayEventEmitterCustom onPaymentSuccess:payment_id andData:[NSMutableDictionary dictionary]];
    }else{
        [RazorpayEventEmitterCustom onPaymentSuccess:payment_id andData:response];
    }
    [razorpay close];
    [self close];
}

- (void)onPaymentError:(int)code
           description:(nonnull NSString *)str
               andData:(NSDictionary *)response {
    NSDictionary *data = response != nil ? response : [NSMutableDictionary dictionary];

    [RazorpayEventEmitterCustom onPaymentError:code description:str andData:data];
    [razorpay close];
    [self close];
}

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    [razorpay webView:webview didFail:navigation withError:error];
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    [razorpay webView:webview didFinish:navigation];
}

- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    [razorpay webView:webview didCommit:navigation];
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    [razorpay webView:webview didFailProvisionalNavigation:navigation withError:error];
}

- (void)handleRotation {
    [self resizeView];
}

- (void)resizeView{
    CGFloat paddingTop = [UIApplication sharedApplication].statusBarHidden ? 0 : 20;
    CGSize size = [[UIScreen mainScreen] bounds].size;
    CGFloat statusHeight = 44;
    [webview setFrame:CGRectMake(0, statusHeight + paddingTop, size.width,
                                 size.height - statusHeight - paddingTop)];
}

- (void)close{

    if (webview != nil){
        [webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]]];
        webview.backgroundColor = [UIColor clearColor];
        [webview stopLoading];
    }

    if (navController != nil){
        [navController dismissViewControllerAnimated:true completion:nil];
    }

    razorpay = nil;

    webview = nil;

    parentVC.view = nil;
    parentVC = nil;

    cancelBtn = nil;

    window.hidden = YES;
    window = nil;

}

@end
