import React from 'react'
import PropTypes from 'prop-types'
import { View, StyleSheet, Platform, TouchableWithoutFeedback } from 'react-native'
import { dictionary } from './dictionary'
import { htmlAttrs } from '../utils/htmlAttrs'
import { selectSystemProps } from '../utils/props/selectSystemProps'
import { useCopy } from '../utils/useCopy'
import { viewProps } from '../utils/props/viewProps'
import { wrapStringsInText } from '../utils/children'
import { variantProp } from '../utils/props/variantProp'
import { applyTextStyles } from '../ThemeProvider/utils/styles'
import { useThemeTokens } from '../ThemeProvider/useThemeTokens'

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

const HALF_FONT_SIZE = 2
const QUARTER_FONT_SIZE = 4
const DEFAULT_LINE_HEIGHT = 1
const LINE_HEIGHT_MULTIPLIER = 2

const selectTextStyle = ({ fontSize, lineHeight }) =>
  Platform.select({
    native: {
      fontSize: fontSize / HALF_FONT_SIZE,
      lineHeight: fontSize,
      position: 'relative',
      top: -(fontSize * lineHeight) / HALF_FONT_SIZE
    },
    web: {
      fontSize,
      lineHeight:
        lineHeight !== DEFAULT_LINE_HEIGHT ? lineHeight : fontSize * LINE_HEIGHT_MULTIPLIER,
      top: -fontSize / QUARTER_FONT_SIZE
    }
  })

export const FootnoteLink = React.forwardRef(
  ({ copy = 'en', content = [], onClick, tokens, variant = {}, ...rest }, ref) => {
    const themeTokens = useThemeTokens('FootnoteLink', tokens, variant)
    const textStyles = applyTextStyles(themeTokens)

    const numbers = Array.isArray(content) ? content : [content]
    const refs = numbers.map(() => React.createRef())

    const handleOnClick = (index) => {
      onClick(numbers[index], refs[index])
    }
    const getCopy = useCopy({ dictionary, copy })

    return (
      <View ref={ref} style={staticStyles.container}>
        {numbers.map((num, index) => (
          <View
            accessibilityLabel={getCopy('a11yLabel')}
            key={num}
            ref={refs[index]}
            {...selectProps(rest)}
          >
            <TouchableWithoutFeedback onPress={handleOnClick} accessibilityRole="button">
              {wrapStringsInText(`${num}${index !== numbers.length - 1 ? ',' : ''}`, {
                style: {
                  ...textStyles,
                  ...staticStyles.text,
                  ...selectTextStyle(themeTokens)
                }
              })}
            </TouchableWithoutFeedback>
          </View>
        ))}
      </View>
    )
  }
)

FootnoteLink.displayName = 'FootnoteLink'
FootnoteLink.__UDS_COMPONENT_NAME__ = 'FootnoteLink'

const copyShape = PropTypes.shape({ a11yLabel: PropTypes.string.isRequired })

FootnoteLink.propTypes = {
  ...selectedSystemPropTypes,
  variant: variantProp.propType,
  /**
   * Use the `copy` prop to either select provided English or French copy by passing 'en' or 'fr' respectively.
   * To provide your own, pass a JSON object with the key `a11yLabel`.
   */
  copy: PropTypes.oneOfType([PropTypes.oneOf(['en', 'fr']), copyShape]),
  /**
   * The footnote number, or multiple numbers if passed as an array.
   * If using an array, a comma-separated group of numbers will be rendered as superscript.
   */
  content: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.arrayOf(PropTypes.number),
    PropTypes.string,
    PropTypes.arrayOf(PropTypes.string)
  ]).isRequired,
  /**
   * A callback function to handle the click of a FootnoteLink.
   */
  onClick: PropTypes.func.isRequired
}

const staticStyles = StyleSheet.create({
  text: {
    position: 'relative',
    textDecorationLine: 'underline'
  },
  container: {
    flexDirection: 'row'
  }
})
