import React from 'react'
import PropTypes from 'prop-types'
import { View } from 'react-native'
import { selectSystemProps } from '../utils/props/selectSystemProps'
import { htmlAttrs } from '../utils/htmlAttrs'
import { viewProps } from '../utils/props/viewProps'
import { a11yProps } from '../utils/props/a11yProps'
import { ProductCard } from '../ProductCard/ProductCard'
import { StackWrap } from '../StackView/StackWrap'

const [selectProps, selectedSystemPropTypes] = selectSystemProps([htmlAttrs, viewProps, a11yProps])

export const ProductCardGroup = React.forwardRef(
  ({ productCards, maxSelection = 1, ...rest }, ref) => {
    const [selectedCardIds, setSelectedCardIds] = React.useState([])

    const handleSelect = (id) => {
      const isAlreadySelected = selectedCardIds.includes(id)
      let updatedSelectedCardIds

      if (isAlreadySelected) {
        updatedSelectedCardIds = selectedCardIds.filter((cardId) => cardId !== id)
      } else if (maxSelection && selectedCardIds.length >= maxSelection) {
        updatedSelectedCardIds = selectedCardIds.filter((_, index) => index !== 0).concat(id)
      } else {
        updatedSelectedCardIds = [...selectedCardIds, id]
      }

      setSelectedCardIds(updatedSelectedCardIds)
    }

    return (
      <View {...selectProps(rest)} ref={ref}>
        <StackWrap direction={{ xs: 'column', lg: 'row' }} space={4}>
          {productCards.map((cardProperties, index) => {
            const cardId = cardProperties.id || index

            return (
              <View key={cardId}>
                <ProductCard
                  key={cardId}
                  cardId={cardId}
                  isSelected={selectedCardIds.includes(cardId)}
                  onSelect={handleSelect}
                  {...cardProperties}
                />
              </View>
            )
          })}
        </StackWrap>
      </View>
    )
  }
)

ProductCardGroup.displayName = 'ProductCardGroup'

ProductCardGroup.propTypes = {
  ...selectedSystemPropTypes,
  /**
   * The maximum number of ProductCards a user may select at once. Defaults to 1.
   * To have no limit and allow any number of selections, pass `null`.
   */
  maxSelection: PropTypes.number,
  /**
   * Props to be passed to the `ProductCard` component.
   * id is required for each card.
   * You may also pass in a custom dictionary object.
   */
  productCards: PropTypes.arrayOf(
    PropTypes.shape({
      id: PropTypes.string.isRequired,
      image: PropTypes.object,
      dictionary: PropTypes.object
    })
  ).isRequired
}
