import React from 'react'
import { StyleProp, Text, TextStyle, View, ViewStyle } from 'react-native'
import { TextStylesV2 } from '../Styles'
import { formatCountShort, notEmpty } from '../util'

/**
 *
 * Set of labels for the Y axis of a graph
 */
export const GraphYAxisScale: React.FC<{
  data: (number | null)[]
  style?: StyleProp<ViewStyle>
  textStyle?: StyleProp<TextStyle>
  dividers?: number
  reverse?: boolean
}> = ({ data, style, textStyle, dividers, reverse }) => {
  const min = 0
  const max = Math.max(...data.filter(notEmpty))
  const divisions = dividers || 1
  const stepPerDivision = max / (divisions + 1)
  const labelValues =
    max > 1
      ? [
          min,
          ...Array.from(Array(divisions), (_, n) => (1 + n) * stepPerDivision),
          max,
        ]
      : [min, max] //Only display 2 labels (0 and 1) if max number of streams is 1
  const labels = reverse
    ? labelValues.reverse().map(formatCountShort)
    : labelValues.map(formatCountShort)
  const fontSize =
    (textStyle as TextStyle)?.fontSize ?? TextStylesV2.micro.fontSize

  // The font we use is not vertically centered, so this calculation just shifts
  // the axis proportionally up by 25% so labels can align with dividers.
  const fontAlignment = fontSize * 0.25
  const marginVertical = -fontSize / 2
  return (
    <View
      style={[
        {
          // We bleed outside of our container to align all labels vertically
          // with the graph dividers
          marginTop: marginVertical - fontAlignment,
          marginBottom: marginVertical,
          justifyContent: 'space-between',
          flexDirection: 'column-reverse',
        },
        style,
      ]}
    >
      {labels.map((label, i) => (
        <Text
          key={i}
          style={[
            textStyle,
            {
              marginBottom:
                // Labels are vertically center aligned, except for the first
                // label which is flush with the bottom of the graph
                i == 0 ? -marginVertical : i == 1 ? marginVertical : 0,
            },
          ]}
        >
          {label}
        </Text>
      ))}
    </View>
  )
}
