import React, { useState } from "react";
import styled from "styled-components";
import { Link } from "@components/index";
import colors from "@theme/colors";
import breakpoints from "@theme/breakpoints";
import DropDownBox from "./DropDownBox";

const Container = styled.div`
  position: relative;

  &:hover {
    &::after {
      content: "";
      position: absolute;
      bottom: 0.4rem;
      left: 0;
      width: 100%;
      border-bottom: 4px solid ${colors.lightBlue};
    }
  }
`;

const StyledLink = styled(Link)`
  display: flex;
  flex-flow: row nowrap;
  justify-content: flex-start;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 2px;
  padding: 1.25rem 0;

  @media screen and (max-width: ${breakpoints.medium}) {
    border-bottom: 1px solid ${colors.lightBlue};
  }
`;

interface NavbarDropdownLinkProps {
  to: string;
  text: string;
  exploded?: boolean; // if exploded, show items directly underneath without a dropdown menu
}

const NavbarDropdownLink: React.FC<NavbarDropdownLinkProps> = ({
  to, text, exploded, children,
}) => {
  const [mouseOverLink, setMouseOverLink] = useState(false);
  const [mouseOverBox, setMouseOverBox] = useState(false);

  const handleMouseEnterLink = () => setMouseOverLink(true);
  const handleMouseLeaveLink = () => setMouseOverLink(false);
  const handleMouseEnterBox = () => setMouseOverBox(true);
  const handleMouseLeaveBox = () => setMouseOverBox(false);

  const open = mouseOverLink || mouseOverBox;

  if (exploded) {
    return (
      <>
        <StyledLink to={to}>
          {text}
        </StyledLink>
        {children}
      </>
    );
  }

  return (
    <Container>
      <StyledLink
        to={to}
        passHref
        onMouseEnter={handleMouseEnterLink}
        onMouseLeave={handleMouseLeaveLink}
      >
        {text}
      </StyledLink>
      <DropDownBox
        onMouseEnter={handleMouseEnterBox}
        onMouseLeave={handleMouseLeaveBox}
        visible={open && !!children}
      >
        {children}
      </DropDownBox>
    </Container>
  );
};

export default NavbarDropdownLink;
