import { Box, Flex, Link as ChakraLink, Stack } from '@chakra-ui/react'
import { motion } from 'framer-motion'
import Link from 'next/link'
import { useRouter } from 'next/router'

import paths from '../paths'

const Container = motion.custom(Flex)

const containerVariants = {
  open: {
    opacity: 1,
    display: 'flex',
  },
  closed: {
    opacity: 0,
    transition: {
      when: 'afterChildren',
    },
    transitionEnd: {
      display: 'none',
    },
  },
}

type NavProps = {
  handleClick: () => void
  variant?: string
}

const Nav: React.FC<NavProps> = ({ handleClick, variant = undefined }) => {
  const { pathname } = useRouter()

  return (
    <Container
      direction="row"
      wrap="wrap"
      h="100%"
      justify="center"
      align="center"
      display="flex"
      variants={containerVariants}
      animate={variant}
    >
      <Stack
        direction={['column', 'column', 'row']}
        spacing={['1rem', '1rem', '2.5rem']}
        position={['absolute', 'static']}
        align="center"
        justify="center"
      >
        {paths.map((path) => {
          const currentLocation = pathname === '/' ? '/' : pathname.substring(1)
          const currentPath = path.path === '/' ? '/' : path.path.substring(1)

          if (currentPath === '/') {
            return null
          }

          const current =
            currentLocation === currentPath ||
            (currentPath !== '/' && currentLocation.includes(currentPath))

          return (
            <Box key={path.path}>
              <Link href={path.path} passHref>
                <ChakraLink
                  onClick={handleClick}
                  fontWeight="bold"
                  color={current ? 'blue' : 'black'}
                  fontSize="md"
                >
                  {path.name}
                </ChakraLink>
              </Link>
            </Box>
          )
        })}
      </Stack>
    </Container>
  )
}

export default Nav
