import React, { memo } from 'react';
import {
  requireNativeComponent,
  StyleSheet,
  View,
  type StyleProp,
  type ViewStyle,
} from 'react-native';

var RNBarcodeScanner = requireNativeComponent('BarcodeScanner') as any;

type Props = {
  style?: StyleProp<ViewStyle> | undefined;
  children: any;
  shouldScan?: boolean;
  onBarcodesDetected: (result: { code: string }) => void;
};

const BarcodeScanner = ({ style, onBarcodesDetected, children }: Props) => {
  const onBarcodesDetectedIOS = ({
    nativeEvent: { barcodes },
  }: {
    nativeEvent: { barcodes: string };
  }) => {
    onBarcodesDetected({ code: barcodes });
  };

  return (
    <View style={[styles.cameraStyle, StyleSheet.flatten(style)]}>
      <View style={styles.scanner}>
        <RNBarcodeScanner
          style={StyleSheet.absoluteFillObject}
          onBarcodesDetected={onBarcodesDetectedIOS}
        />
      </View>
      <View style={[StyleSheet.absoluteFillObject, styles.center]}>
        {children}
      </View>
    </View>
  );
};

export default memo(BarcodeScanner);

const styles = StyleSheet.create({
  cameraStyle: { flex: 1, width: '100%' },
  scanner: { flex: 1, width: '100%' },
  center: {
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'transparent',
  },
});
