import React, { useState, cloneElement } from 'react'
import PropTypes from 'prop-types'
import { Swipeable } from 'react-swipeable'
import { noop } from '../../utils'

export const FullGroup = (props) => {
  const {
    children,
    onEnter = noop,
    onExit = noop,
  } = props
  const [selected, setSelected] = useState(0)
  const slides = React.Children.count(children)
  const isFirst = selected === 0
  const isLast = selected === slides - 1
  const next = isLast
    ? onExit
    : () => setSelected(selected + 1)
  const previous = isFirst
    ? onEnter
    : () => setSelected(selected - 1)
  const augmentedChildren = React.Children.map(
    children,
    (child, index) => {
      const shouldSwipe = !!(typeof child.props.swipe === 'undefined' || child.props.swipe)
      const visible = selected === index

      // child.type.name is not working with minified code, this is a workaround
      if (child.props.nestSwipe) {
        return visible
          ? cloneElement(child, {
            onEnter: previous,
            onExit: next,
          })
          : null
      }
      const fullSection = cloneElement(child, {
        visible
      })
      return shouldSwipe
        ? (
          <Swipeable
            preventDefaultTouchmoveEvent={true}
            onSwipedUp={next}
            onSwipedDown={previous}>
            {fullSection}
          </Swipeable>
        )
        : fullSection
    }
  )

  return (
    <>
      {augmentedChildren}
    </>
  )
}

FullGroup.propTypes = {
  onEnter: PropTypes.func,
  onExit: PropTypes.func,
}

FullGroup.displayName = 'FullGroup'