import { HeapIgnore } from '@contentsquare/react-native-autocapture';
import React from 'react';
import { Platform } from 'react-native';
import { CSQMaskProps } from '../../types/types';
import { getComponentDisplayName, getHeapIgnoreProps } from '../../utils/utils';

const CSQMaskedView =
  Platform.OS === 'ios'
    ? require('../../core/specs/CSQMaskedViewNativeComponent').default
    : require('./CSQMaskedView').default;

const CSQUnmaskedView =
  Platform.OS === 'ios'
    ? require('../../core/specs/CSQUnmaskedViewNativeComponent').default
    : require('./CSQUnmaskedView').default;

type ParentProps = {
  children: React.ReactNode;
};

export const withCSQMask = <P, T>(
  WrappedComponent: React.JSXElementConstructor<P>,
  maskOptions?: CSQMaskProps
) => {
  const WithCSQMask = (props: P & ParentProps, ref: React.Ref<T>) => {
    const { isSessionReplayMasked = true } = maskOptions || {};

    const heapIgnoreProps = getHeapIgnoreProps(maskOptions);

    const CSQComponent = isSessionReplayMasked
      ? CSQMaskedView
      : CSQUnmaskedView;

    return (
      <HeapIgnore {...heapIgnoreProps}>
        <CSQComponent>
          <WrappedComponent {...props} ref={ref}>
            {props.children}
          </WrappedComponent>
        </CSQComponent>
      </HeapIgnore>
    );
  };

  const displayName = `withCSQMask(${getComponentDisplayName(
    WrappedComponent,
    'WrappedComponent'
  )})`;

  WithCSQMask.displayName = displayName;

  // @ts-expect-error - TypeScript has difficulty inferring the correct types for forwardRef with generic props
  const ForwardedComponent = React.forwardRef<T, P>(WithCSQMask);
  ForwardedComponent.displayName = displayName;

  return ForwardedComponent;
};
