import React from 'react'
import { View } from 'react-native'

import PropTypes from 'prop-types'
import { StackView } from '../../StackView/StackView'

import { useCarousel } from '../CarouselContext'
import { CarouselTabsPanelItem } from './CarouselTabsPanelItem'

const selectTabPanelStyle = () => ({
  backgroundColor: 'transparent'
})

export const CarouselTabsPanel = React.forwardRef(({ items }, ref) => {
  const { activeIndex, goTo } = useCarousel()
  const nextFocusRef = React.useRef()
  const firstTabRef = React.useRef()
  const [isInverse, setIsInverse] = React.useState(false)

  const lastTabSelected = activeIndex === items.length - 1

  // Get current select tab style
  React.useEffect(() => {
    const [selectedVariantIsInverse] = items.filter((_, index) => index === activeIndex)
    setIsInverse(selectedVariantIsInverse?.inverse)
  }, [items, activeIndex])

  // TODO: figure out a better cross-brand way to specify subcomponent variants.
  // For now, this picks an Allium variant, and does nothing in brands that lack it.
  // See similar comment in Carousel and https://github.com/telus/universal-design-system/issues/1549
  const dividerVariant = { decorative: true, inverse: isInverse }

  return (
    <View style={selectTabPanelStyle()}>
      <StackView
        direction="row"
        space={3}
        divider={{
          variant: dividerVariant,
          accessibilityRole: 'presentation',
          accessibilityOrientation: null
        }}
        ref={ref}
        accessibilityRole="tablist"
      >
        {items.map(({ title, onPress, inverse, ...panelItemProps }, index) => {
          const selected = index === activeIndex
          const isNext = index === activeIndex + 1

          // Selected item should be always unfocusable and unpressable
          const handlePress = selected
            ? undefined
            : (event) => {
                if (typeof onPress === 'function') onPress(event, index)
                goTo(index)
              }

          return (
            <CarouselTabsPanelItem
              ref={(isNext && nextFocusRef) || (index === 0 && firstTabRef) || null}
              key={title}
              title={title}
              selected={selected}
              onPress={handlePress}
              variant={{ inverse: isInverse }}
              {...panelItemProps}
            />
          )
        })}
      </StackView>
      {/* TODO: integrate with skiplink, replace this with focusing skiplink target */}
      <View focusable accessible ref={lastTabSelected ? nextFocusRef : null} />
    </View>
  )
})
CarouselTabsPanel.displayName = 'CarouselTabsPanel'
CarouselTabsPanel.propTypes = {
  items: PropTypes.arrayOf(PropTypes.shape(CarouselTabsPanelItem.propTypes || {})),
  // Color defined by `CarouselItem` variant otherwise fallback to transparent
  contentBackgroundColor: PropTypes.string
}
