import React from 'react'
import { AnimatePresence } from '@tamagui/animate-presence'
import { ArrowLeft, ArrowRight } from '@tamagui/lucide-icons-2'

import { Button, Image, XStack, YStack, styled } from 'tamagui'

// @ts-ignore
import photo1 from '../../public/photo1.jpg'
// @ts-ignore
import photo2 from '../../public/photo2.jpg'
// @ts-ignore
import photo3 from '../../public/photo3.jpg'

export const images = [photo1, photo2, photo3].map((x) => (x as any).src || x)

const GalleryItem = styled(YStack, {
  z: 1,
  x: 0,
  opacity: 1,
  fullscreen: true,

  variants: {
    // 1 = right, 0 = nowhere, -1 = left
    going: {
      ':number': (going) => ({
        enterStyle: {
          x: going > 0 ? 1000 : -1000,
          opacity: 0,
        },
        exitStyle: {
          zIndex: 0,
          x: going < 0 ? 1000 : -1000,
          opacity: 0,
        },
      }),
    },
  } as const,
})

const wrap = (min: number, max: number, v: number) => {
  const rangeSize = max - min
  return ((((v - min) % rangeSize) + rangeSize) % rangeSize) + min
}

export function AnimationsPresenceDemo() {
  const [[page, going], setPage] = React.useState([0, 0])

  const imageIndex = wrap(0, images.length, page)
  const paginate = (going: number) => {
    setPage([page + going, going])
  }

  return (
    <XStack
      overflow="hidden"
      bg="#000"
      position="relative"
      height={300}
      width="100%"
      items="center"
    >
      <AnimatePresence initial={false} custom={{ going }}>
        <GalleryItem key={page} transition="slow" going={going}>
          <Image src={images[imageIndex]} width={820} height={300} objectFit="cover" />
        </GalleryItem>
      </AnimatePresence>

      <Button
        aria-label="Carousel left"
        icon={ArrowLeft}
        size="$5"
        position="absolute"
        l="$4"
        circular
        onPress={() => paginate(-1)}
        boxShadow="0 0 10px rgba(0,0,0,0.5)"
        z={100}
      />

      <Button
        aria-label="Carousel right"
        icon={ArrowRight}
        size="$5"
        position="absolute"
        r="$4"
        circular
        onPress={() => paginate(1)}
        boxShadow="0 0 10px rgba(0,0,0,0.5)"
        z={100}
      />
    </XStack>
  )
}
