import React from 'react'
import { StyleSheet, View, Text, Platform } from 'react-native'
import { A11yText } from '../../A11yText/A11yText'
import { renderTypography } from './renderTypography'
import { renderFootnoteLinks } from './renderFootnoteLinks'

const selectStrikeThroughStyles = ({ strikeThroughColor }) => ({
  textDecorationColor: strikeThroughColor
})

const selectFootnoteLinksStyles = ({ bottomLinksMarginLeft }) => ({
  marginLeft: bottomLinksMarginLeft
})

const renderCurrencySymbol = (
  currencySymbol,
  currencySymbolTypographyTokens,
  ratePosition,
  fontColor
) => renderTypography(`${currencySymbol}`, currencySymbolTypographyTokens, ratePosition, fontColor)

const renderAmount = (
  amount,
  amountTypographyTokens,
  strikeThrough,
  a11yText,
  fontColor,
  themeTokens
) => {
  const amountText = renderTypography(amount, amountTypographyTokens, undefined, fontColor) // undefined is ratePosition
  if (strikeThrough) {
    return (
      <>
        <A11yText text={a11yText} />
        <Text style={[staticStyles.strikeThroughContainer, selectStrikeThroughStyles(themeTokens)]}>
          {amountText}
        </Text>
      </>
    )
  }

  return amountText
}

export const renderPrice = (
  price,
  rateText,
  ratePosition,
  signDirection,
  currencySymbol,
  currencySymbolTypographyTokens,
  amountTypographyTokens,
  centsTypographyTokens,
  rateTypographyTokens,
  fontColor,
  strikeThrough,
  a11yText,
  bottomText,
  bottomLinksMarginLeft,
  footnoteLinks,
  onClickFootnote,
  themeTokens,
  isPriceBaseline
) => {
  const priceString = price
  const lastDotPosition = priceString.lastIndexOf('.')
  const lastCommaPosition = priceString.lastIndexOf(',')
  const [separator, separatorPosition] =
    lastDotPosition > lastCommaPosition ? ['.', lastDotPosition] : [',', lastCommaPosition]

  // If the separator is at the fourth character from the end of the string or more, it's most probably
  // a part of the amount, and the cents are not included in the price string
  const EXCLUDE_CENTS = 3
  const hasCents =
    separatorPosition !== -1 && separatorPosition >= priceString.length - EXCLUDE_CENTS
  const amount = hasCents ? priceString.substring(0, separatorPosition) : priceString
  const cents = hasCents ? priceString.substring(separatorPosition + 1) : null

  const footnoteLinkPositionStyles = rateText
    ? staticStyles.footnoteLinksWithoutBottomText
    : staticStyles.footnoteLinksWithoutBottomTextAndRateText

  const MAX_FOOTNOTE_LINKS_ALLOWED = 3

  return (
    <>
      <View
        style={
          ratePosition === 'bottom'
            ? staticStyles.priceContainerColumn
            : staticStyles.priceContainerRow
        }
      >
        <View style={staticStyles.priceContainer}>
          {signDirection === 'left' ? (
            <Text>
              {renderCurrencySymbol(
                currencySymbol,
                currencySymbolTypographyTokens,
                ratePosition,
                fontColor
              )}
            </Text>
          ) : null}
          <Text>
            {renderAmount(
              amount,
              amountTypographyTokens,
              strikeThrough,
              a11yText,
              fontColor,
              themeTokens
            )}
            {isPriceBaseline &&
              cents &&
              renderAmount(
                `${separator}${cents}`,
                centsTypographyTokens,
                strikeThrough,
                a11yText,
                fontColor,
                themeTokens
              )}
          </Text>
          {cents && !isPriceBaseline
            ? renderTypography(`${separator}${cents}`, centsTypographyTokens, undefined, fontColor)
            : null}
          {signDirection === 'right' ? (
            <Text style={staticStyles.currencySymbol}>
              {renderCurrencySymbol(
                currencySymbol,
                currencySymbolTypographyTokens,
                ratePosition,
                fontColor
              )}
            </Text>
          ) : null}
        </View>
        {rateText ? (
          <Text
            style={
              ratePosition === 'bottom'
                ? staticStyles.rateTextVerticalPosition
                : [staticStyles.rateTextPosition, staticStyles.rateTextVerticalPosition]
            }
          >
            {renderTypography(rateText, rateTypographyTokens, ratePosition, fontColor)}
          </Text>
        ) : null}
        {!bottomText && footnoteLinks?.length <= MAX_FOOTNOTE_LINKS_ALLOWED ? (
          <Text
            style={[
              footnoteLinkPositionStyles,
              selectFootnoteLinksStyles({ bottomLinksMarginLeft })
            ]}
          >
            {renderFootnoteLinks(footnoteLinks, themeTokens, onClickFootnote)}
          </Text>
        ) : null}
      </View>
      {!bottomText && footnoteLinks?.length > MAX_FOOTNOTE_LINKS_ALLOWED ? (
        <View style={staticStyles.verticalFootnoteLinkContainer}>
          {renderFootnoteLinks(footnoteLinks, themeTokens, onClickFootnote)}
        </View>
      ) : null}
    </>
  )
}

const staticStyles = StyleSheet.create({
  priceContainerRow: {
    flexDirection: 'row'
  },
  priceContainerColumn: {
    flexDirection: 'column'
  },
  priceContainer: {
    flexDirection: 'row',
    alignSelf: 'flex-start',
    marginTop: 4
  },
  currencySymbol: {
    paddingLeft: 4
  },
  verticalFootnoteLinkContainer: {
    ...Platform.select({
      ios: { top: 10 },
      android: { top: -2 }
    })
  },
  footnoteLinksWithoutBottomText: {
    ...Platform.select({
      ios: { alignSelf: 'flex-end', top: -10 },
      android: { alignSelf: 'center', top: -14 }
    })
  },
  footnoteLinksWithoutBottomTextAndRateText: {
    ...Platform.select({
      ios: { alignSelf: 'center' },
      android: { alignSelf: 'flex-start' }
    })
  },
  strikeThroughContainer: {
    textDecorationLine: 'line-through',
    textDecorationThickness: '1px'
  },
  rateTextPosition: {
    alignSelf: 'flex-end'
  },
  rateTextVerticalPosition: {
    top: -8
  }
})
