import {
  Box,
  Flex,
  Image,
  Link as ChakraLink,
  Spacer,
  useBreakpointValue,
} from '@chakra-ui/react'
import { motion } from 'framer-motion'
import Link from 'next/link'
import React, { useEffect, useState } from 'react'
import Headroom from 'react-headroom'

import MenuButton from './MenuButton'
import Nav from './Nav'

export const closedNavHeight = '76px'

const headerVariants = {
  open: {
    height: '100vh',
    transition: {
      ease: 'easeInOut',
      duration: 0.3,
      when: 'beforeChildren',
    },
  },
  closed: {
    height: closedNavHeight,
    transition: {
      when: 'afterChildren',
      ease: 'easeInOut',
      duration: 0.3,
    },
  },
}

const MotionFlex = motion.custom(Flex)

const Header: React.FC = () => {
  const [navOpen, setNavOpen] = useState(false)
  const isMobile = useBreakpointValue<boolean>({
    base: true,
    sm: true,
    md: true,
    lg: false,
  })

  useEffect(() => {
    document.documentElement.style.setProperty('--nav-height', closedNavHeight)
  })

  const toggleNav = () => {
    setNavOpen(!navOpen)

    const body = document.getElementsByTagName('body')[0]
    body.classList.toggle('lock-scroll')
  }

  const closeNav = () => {
    setNavOpen(false)

    const body = document.getElementsByTagName('body')[0]
    body.classList.remove('lock-scroll')
  }

  useEffect(() => {
    if (!isMobile && navOpen) {
      closeNav()
    }
  }, [isMobile, navOpen])

  return (
    <Headroom style={{ zIndex: 2 }}>
      <MotionFlex
        layout="position"
        w="100%"
        direction="column"
        position="absolute"
        variants={headerVariants}
        initial="closed"
        animate={navOpen ? 'open' : 'closed'}
        bg="white"
      >
        <Flex h={closedNavHeight} align="center" px={[null, null, '2rem']}>
          <Link href="/" passHref>
            <ChakraLink onClick={() => closeNav()}>
              <Image src="/images/logo.svg" alt="Logo del estudio" p="1rem" h="100%" />
            </ChakraLink>
          </Link>
          <Spacer />
          {isMobile ? (
            <MenuButton isOpen={navOpen} handleClick={() => toggleNav()} />
          ) : (
            <Nav variant="open" handleClick={() => closeNav()} />
          )}
        </Flex>
        {isMobile ? <Nav handleClick={() => closeNav()} /> : null}
      </MotionFlex>
      <Box w="100%" h={closedNavHeight} />
    </Headroom>
  )
}

export default Header
