import React from 'react'
import { View as NativeView, StyleSheet } from 'react-native'
import PropTypes from 'prop-types'
import { useTheme } from '../../ThemeProvider/useTheme'

/**
 * Identical to React Native's View and supporting all the same props, but with:
 *  - a zIndex: 'auto' style added to prevent unexpectedly causing children to overlap other elements from other stacking contexts
 */
export const BaseView = React.forwardRef(({ children, style, ...rest }, ref) => {
  const { themeOptions } = useTheme()
  const styleProp = Array.isArray(style) ? [...style] : [style]

  if (!themeOptions.forceZIndex) {
    styleProp.unshift(styles.resetZIndex)
  }

  return (
    <NativeView {...rest} style={styleProp} ref={ref}>
      {children}
    </NativeView>
  )
})

BaseView.displayName = 'BaseView'

const styles = StyleSheet.create({
  resetZIndex: {
    zIndex: 'auto'
  }
})

BaseView.propTypes = {
  /**
   * Content rendered inside the view.
   */
  children: PropTypes.node,
  /**
   * React Native style object, or array of style objects, applied to the view.
   */
  style: PropTypes.oneOfType([PropTypes.object, PropTypes.array])
}
