import React from 'react'
import { View, StyleSheet, Platform } from 'react-native'
import PropTypes from 'prop-types'
import { useThemeTokens } from '../ThemeProvider/useThemeTokens'
import { applyOuterBorder } from '../ThemeProvider/utils/styles'
import { a11yProps } from '../utils/props/a11yProps'
import { getTokensPropType } from '../utils/props/tokens'
import { selectSystemProps } from '../utils/props/selectSystemProps'
import { variantProp } from '../utils/props/variantProp'
import { viewProps } from '../utils/props/viewProps'
import { Icon } from '../Icon/Icon'

const [selectProps, selectedSystemPropTypes] = selectSystemProps([a11yProps, viewProps])

const selectInnerContainerStyles = ({ borderRadius, width, backgroundColor }) => ({
  borderRadius,
  width,
  backgroundColor
})

const selectIconTokens = ({ iconSize, iconColor, iconScale = 1 }) => ({
  size: iconSize,
  color: iconColor,
  scale: iconScale
})

/**
 * `TooltipButton` is a helper component used as a default control for the `Tooltip` component.
 * In fact though, it isn't actually a pressable - it's meant to be used as pressable's content.
 * Due to this any interaction states (e.g. pressed, hover, etc.) has to be passed down to it as a prop.
 */
export const TooltipButton = React.forwardRef(
  ({ pressableState, tokens, variant, ...rest }, ref) => {
    const themeTokens = useThemeTokens('TooltipButton', tokens, variant, pressableState)

    const { icon: IconComponent } = themeTokens

    return (
      <View
        style={[
          applyOuterBorder(themeTokens),
          themeTokens.outerBorderWidth && {
            margin: -themeTokens.outerBorderWidth
          },
          staticStyles.bubblePointerEvents
        ]}
        {...selectProps(rest)}
        ref={ref}
      >
        <View style={selectInnerContainerStyles(themeTokens)}>
          {IconComponent && <Icon icon={IconComponent} tokens={selectIconTokens(themeTokens)} />}
        </View>
      </View>
    )
  }
)

TooltipButton.displayName = 'TooltipButton'

const staticStyles = StyleSheet.create({
  bubblePointerEvents: {
    ...Platform.select({
      web: {
        pointerEvents: 'none'
      }
    })
  }
})

TooltipButton.propTypes = {
  ...selectedSystemPropTypes,
  /**
   * Used as appearances when resolving theme tokens.
   */
  pressableState: PropTypes.shape({
    pressed: PropTypes.bool,
    hover: PropTypes.bool,
    focus: PropTypes.bool
  }),
  tokens: getTokensPropType('TooltipButton'),
  variant: variantProp.propType
}
