// Copyright © 2022 Olo Inc. All rights reserved.
// This software is made available under the Olo Pay SDK License (See LICENSE.md file)
import useOloPayNativeModule from './useOloPayNativeModule';
import { NativeModules, Platform, findNodeHandle } from 'react-native';
import type { PaymentMethod } from '../definitions';

const ViewManager = NativeModules.PaymentCardDetailsFormManager;
const AndroidViewManager = useOloPayNativeModule();

const blur = async (ref: any): Promise<void> => {
  let nodeHandle = findNodeHandle(ref.current);
  if (Platform.OS === 'ios') {
    return await ViewManager.blur(nodeHandle);
  } else {
    return await AndroidViewManager.paymentCardDetailsFormBlur(nodeHandle);
  }
};

const focus = async (ref: any): Promise<void> => {
  let nodeHandle = findNodeHandle(ref.current);
  if (Platform.OS === 'ios') {
    return await ViewManager.focus(nodeHandle);
  } else {
    return await AndroidViewManager.paymentCardDetailsFormFocus(nodeHandle);
  }
};

const clear = async (ref: any): Promise<void> => {
  let nodeHandle = findNodeHandle(ref.current);
  if (Platform.OS === 'ios') {
    return await ViewManager.clear(nodeHandle);
  } else {
    return await AndroidViewManager.paymentCardDetailsFormClear(nodeHandle);
  }
};

const createPaymentMethod = async (ref: any): Promise<PaymentMethod> => {
  let nodeHandle = findNodeHandle(ref.current);
  if (Platform.OS === 'ios') {
    return await ViewManager.createPaymentMethod(nodeHandle);
  } else {
    return await AndroidViewManager.paymentCardDetailsFormCreatePaymentMethod(
      nodeHandle
    );
  }
};

export interface PaymentCardDetailsFormNativeMethods {
  focus(ref: any): Promise<void>;
  blur(ref: any): Promise<void>;
  clear(ref: any): Promise<void>;
  createPaymentMethod(ref: any): Promise<PaymentMethod>;
}

export default function usePaymentCardDetailsFormManager(): PaymentCardDetailsFormNativeMethods {
  return {
    blur,
    clear,
    focus,
    createPaymentMethod,
  };
}
