import React from 'react'
import { Pressable, StyleSheet } from 'react-native'
import PropTypes from 'prop-types'

/**
 * @typedef {import('react-native').PressableProps} PressableProps
 */

/**
 * InlinePressable is an alternative to React Native's Pressable that works better when nested
 * inline inside Text. It accepts the same props as React Native's Pressable.
 *
 * On Web it simply passes its props to Pressable and defaults to `inline-flex` instead of `flex`.
 *
 * @param {PressableProps} PressableProps
 */
export const InlinePressable = React.forwardRef(
  ({ children, inlineFlex = true, style, ...props }, ref) => (
    <Pressable
      ref={ref}
      style={(pressState) => [
        typeof style === 'function' ? style(pressState) : style,
        staticStyles[inlineFlex ? 'inlineFlex' : 'inline']
      ]}
      {...props}
    >
      {(pressState) => (typeof children === 'function' ? children(pressState) : children)}
    </Pressable>
  )
)

InlinePressable.displayName = 'InlinePressable'

InlinePressable.propTypes = {
  children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),
  inlineFlex: PropTypes.bool,
  style: PropTypes.oneOfType([PropTypes.object, PropTypes.array, PropTypes.func])
}

const staticStyles = StyleSheet.create({
  inline: {
    // Stop Pressable defaulting to (block) flex
    display: 'inline'
  },
  inlineFlex: {
    display: 'inline-flex'
  }
})
