// Copyright © 2022 Olo Inc. All rights reserved.
// This software is made available under the Olo Pay SDK License (See LICENSE.md file)

import {
  type HostComponent,
  type NativeSyntheticEvent,
  Platform,
  requireNativeComponent,
  StyleSheet,
} from 'react-native';
import type { DigitalWalletButtonNativeProps } from './definitions/DigitalWalletButtonNativeTypes';
import React, { useCallback } from 'react';
import type { DigitalWalletButtonProps } from '../definitions';

// Support both Old and New Architecture
const isFabricEnabled = () => {
  // @ts-ignore
  return global.nativeFabricUIManager != null;
};

let NativeButton: HostComponent<DigitalWalletButtonNativeProps>;

if (isFabricEnabled()) {
  try {
    NativeButton =
      require('./specs/DigitalWalletButtonNativeComponent').default;
  } catch (e) {
    NativeButton = requireNativeComponent('DigitalWalletButton');
  }
} else {
  NativeButton = requireNativeComponent('DigitalWalletButton');
}

export const DigitalWalletButton: React.FC<DigitalWalletButtonProps> = ({
  onPress,
  disabled,
  applePayConfig,
  googlePayConfig,
  styles,
  ...props
}) => {
  const onPressEventHandler = useCallback(
    (_: NativeSyntheticEvent<undefined>) => {
      onPress?.();
    },
    [onPress]
  );

  return (
    <NativeButton
      style={[defaultStyles.nativeCard, styles]}
      onClickedEvent={onPressEventHandler}
      googlePayConfig={googlePayConfig}
      applePayConfig={applePayConfig}
      isEnabled={!disabled}
      {...props}
    />
  );
};

const defaultStyles = StyleSheet.create({
  nativeCard: {
    minWidth: 80,
    ...Platform.select({
      android: {
        minHeight: 40,
      },
      default: {
        minHeight: 30,
      },
    }),
  },
});
