import React from 'react'
import {
  HorizontalScroll,
  HorizontalScrollButton,
  horizontalScrollUtils,
  StackView,
  useThemeTokens,
  useViewport
} from '@telus-uds/components-base'
import { View } from 'react-native-web'
import PropTypes from 'prop-types'

const { useItemPositions } = horizontalScrollUtils

const VideoSlider = React.forwardRef(({ children }, ref) => {
  const viewport = useViewport()
  const [itemPositions] = useItemPositions()
  const [containerWidth, setContainerWidth] = React.useState(null)
  const { previousIcon: PreviousIcon, nextIcon: NextIcon } = useThemeTokens('VideoPickerSlider')

  const onLayout = ({
    nativeEvent: {
      layout: { width }
    }
  }) => {
    setContainerWidth(width)
  }

  const itemsGap = 32 // '5' on spacing scale
  const itemsCount = viewport === 'lg' || viewport === 'xl' ? 4 : 3
  const itemGapPortioned = ((itemsCount - 1) * itemsGap) / itemsCount
  const itemWidth =
    containerWidth === null
      ? // For first render, we don't know container width, so avoid flicker with static % width
        `calc(${Math.round(100 / itemsCount)}% - ${Math.round(itemGapPortioned)}px)`
      : // After first render, can't use % widths because parent is > 100% width horizontal scroll area
        Math.max(
          containerWidth / itemsCount - itemGapPortioned,
          0 // Prevent negative width breaking layout on very narrow containers
        )

  const content = (
    <StackView space={5} direction="row" accessibilityRole="radiogroup" tokens={{ flexGrow: 1 }}>
      {React.Children.map(children, (child, index) =>
        React.cloneElement(child, {
          index,
          itemPositions,
          width: itemWidth
        })
      )}
    </StackView>
  )

  const overflow = containerWidth === null && { overflow: 'hidden' }
  const horizontalScrollTokens = {
    nextIcon: NextIcon,
    previousIcon: PreviousIcon,
    gutter: 0,
    borderBottomWidth: 0,
    borderBottomColor: 'transparent',
    buttonClearance: 0
  }
  return (
    <View onLayout={onLayout} style={overflow} ref={ref}>
      {containerWidth === null ? (
        // Use a 100% width non-scrollable parent until containerWidth is known, to avoid flicker
        content
      ) : (
        <HorizontalScroll
          ScrollButton={HorizontalScrollButton}
          itemPositions={itemPositions}
          tokens={horizontalScrollTokens}
        >
          {content}
        </HorizontalScroll>
      )}
    </View>
  )
})

VideoSlider.displayName = 'VideoSlider'

VideoSlider.propTypes = {
  children: PropTypes.node
}

export default VideoSlider
