import React from 'react'
import PropTypes from 'prop-types'
import { View } from 'react-native'
import { useCarousel } from './CarouselContext'
import { CarouselThumbnail } from './CarouselThumbnail'
import { StackWrap } from '../StackView/StackWrap'
import { useThemeTokens } from '../ThemeProvider/useThemeTokens'
import { useViewport } from '../ViewportProvider/useViewport'

export const CarouselThumbnailNavigation = React.forwardRef(({ thumbnails = [] }, ref) => {
  const viewport = useViewport()
  const { alignItems } = useThemeTokens('CarouselThumbnail', {}, { viewport })
  const { totalItems } = useCarousel()
  if (thumbnails.length !== totalItems) {
    throw new Error('Thumbnail set provided does not match the number of slides in the carousel')
  }
  const { containerPaddingTop: thumbnailContainerPaddingTop } = useThemeTokens('CarouselThumbnail')
  const stackWrapTokens = {
    justifyContent: 'flex-start'
  }
  const containerStyles = {
    justifyContent: 'center',
    alignItems,
    paddingTop: thumbnailContainerPaddingTop
  }

  return (
    <View style={containerStyles}>
      <StackWrap direction="row" tokens={stackWrapTokens} space={2} ref={ref}>
        {thumbnails.map(({ accessibilityLabel, alt, isVideo, src }, index) => (
          <CarouselThumbnail
            accessibilityLabel={accessibilityLabel}
            alt={alt}
            index={index}
            isVideo={isVideo}
            key={src}
            src={src}
          />
        ))}
      </StackWrap>
    </View>
  )
})
CarouselThumbnailNavigation.displayName = 'CarouselThumbnailNavigation'
CarouselThumbnailNavigation.propTypes = {
  /**
   * An array of objects containing information on the thumbnail images.
   */
  thumbnails: PropTypes.arrayOf(
    PropTypes.shape({
      /** Accessibility label for the thumbnail image, used by assistive technologies. */
      accessibilityLabel: PropTypes.string,
      /** Alternative text for the thumbnail image, displayed when the image cannot be rendered. */
      alt: PropTypes.string,
      /** When true, renders a play icon overlay on the thumbnail to indicate that the slide contains a video. */
      isVideo: PropTypes.bool,
      /** URL or path of the thumbnail image. When used with `isVideo`, this should be the video's poster/preview image. */
      src: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
    })
  ).isRequired
}
