/**
 * @format
 */
import {Box, Button, Flex, VStack} from '@chakra-ui/react'
import React, {ReactNode, useState} from 'react'

interface CarouselOptions {
  /**
   * If `true`, the carousel will start to autoLoop.
   */
  autoStart: boolean
  /**
   * If `true`, the carousel will go back to the first slide, if there no further slides to move to.
   */
  loop: boolean
  /**
   * Specifies the number of slides in the carousel
   */
  pageLength: number
  /**
   * Determines how fast or slow the pages transition to the next. Slow = 750ms; Normal = 500ms; Fast = 350ms
   */
  transitionSpeed?: 'slow' | 'normal' | 'fast'
  /**
   * The pages or the content of the Carousel
   */
  children: ReactNode
}

export const CarouselPage = ({children}: {children: ReactNode}) => (
  <Box rounded="lg" p="4" w={`100%`} maxW="100%">
    {children}
  </Box>
)
export const Carousel = ({opts}: {opts: CarouselOptions}) => {
  const pageCompLength = []
  const selectedDotColor = '#E03C31'
  const normalColor = '#E4E4E7'
  const [selectedIndex, setSelectedIndex] = useState<number>(0)
  let transitionTime

  if (opts.transitionSpeed === 'slow') {
    transitionTime = '350ms'
  } else if (opts.transitionSpeed === 'fast') {
    transitionTime = '750ms'
  } else {
    transitionTime = '500ms'
  }

  for (let i = 0; i < opts.pageLength; i++) {
    pageCompLength.push(i)
  }

  return (
    <Box>
      <VStack w="100%">
        <Box w="100%" overflow="hidden">
          <Flex
            ml={`-${selectedIndex * 100}%`}
            sx={{transition: transitionTime}}
            w={`${opts.pageLength * 100}%`}
            wrap={'nowrap'}
            flexGrow="1"
          >
            {opts.children}
          </Flex>
        </Box>
        <Flex alignItems="center" justifyContent="center">
          {pageCompLength.map((i: any) => (
            <Button
              key={`${i}_carouselButton`}
              m="0"
              p="0"
              minW="20px !important"
              width="20px !important"
              borderWidth="0"
              onClick={() => setSelectedIndex(i)}
            >
              <svg width="8px" height="8px" fill="none" xmlns="http://www.w3.org/2000/svg">
                <circle cx="4" cy="4" r="4" fill={i === selectedIndex ? selectedDotColor : normalColor} />
              </svg>
            </Button>
          ))}
        </Flex>
      </VStack>
    </Box>
  )
}
