import React, { useEffect } from 'react';
import {
  Platform,
  View,
  ViewStyle,
} from 'react-native';
import { UNComponentsError, UNComponentsErrorCodes, UNComponentsErrorData } from '../../types/shared';
import { useIsJailbrokeDevice } from '../../hooks/useIsJailbrokeDevice';
import { useSnapshotProtection } from '../../hooks/useSnapshotProtection';
import { RootState } from '../../store';
import { useSelector } from 'react-redux';

type UnitSecureViewProps = {
  style?: ViewStyle;
  children: React.ReactNode;
  onLoadError?: (error: UNComponentsError) => void;
  fallback?: React.ReactNode;
};

const UNBaseView = (props: UnitSecureViewProps) => {
  useSnapshotProtection();
  const customerToken = useSelector((state: RootState) => state.configuration.customerToken);
  const isJailbroke = useIsJailbrokeDevice();

  useEffect(() => {
    if (isJailbroke) {
      props.onLoadError && props.onLoadError({errors: [{title: 'Device is Jailbroke'}]});
    }
  }, [props, isJailbroke]);

  if (isJailbroke) {
    return null;
  }
  if (props.onLoadError && !customerToken) {
    props.onLoadError(
      {
        errors: [{ code: UNComponentsErrorCodes.MISSING_TOKEN } as UNComponentsErrorData]
      }
    );
    if (props.fallback) {
      return <>{props.fallback}</>;
    }
  }

  if (Platform.OS == 'android') {
    // eslint-disable-next-line @typescript-eslint/no-var-requires
    const UnitAndroidSecureView = require('../UNSecureView/UNSecureViewNativeComponent.android').default;
    return <UnitAndroidSecureView filterTouchesWhenObscured={true} {...props}/>;
  } else {
    return (
      <View {...props} />
    );
  }
};

export default UNBaseView;
