// @flow
import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import type { Link, Member } from '../../types';
import ApoliticalLogo from '../Atom/ApoliticalLogo/ApoliticalLogo';
import Chevron from '../Atom/Chevron/Chevron';
import defaultTheme from '../../Theme/ApoliticalBrand';

const { color } = defaultTheme;

type Props = {
  tabs: Array<Link>,
  me: ?Member,
};

const DropDownMenu = styled.div`
  display: flex;
  height: 100%;
`;

const MobileLogo = styled(ApoliticalLogo)`
  display: inline-flex;
  height: ${defaultTheme.remify(24)};
  margin: auto 0;
`;

const TabChevron = styled(Chevron)`
  display: flex;
  align-items: center;
  margin-left: ${defaultTheme.remify(15)};
  transform: ${({ active }) => (active ? 'scaleY(-1)' : 'scaleY(1)')};
  filter: ${({ active }) => (active ? 'FlipV' : 'none')};
  transition: filter 0.4s, transform 0.4s;
  cursor: pointer;
  color: ${color.purple};
`;

const Nav = styled.nav`
  position: absolute;
  left: 0;
`;

const TabMenu = styled.ul`
display: flex;
  height: ${({ active }) => (active ? 'unset' : '0')};

  width: 100vw;
  overflow: hidden;

  position: absolute;
  top: ${defaultTheme.remify(40)};
  margin-top: ${defaultTheme.remify(20)};
  padding-top: ${defaultTheme.remify(20)};


  flex-direction: column;

  box-shadow: 0 10px 10px 0 rgba(0, 0, 0, 0.1);
  background-color: white;

  font-size: ${defaultTheme.remify(16)};
  line-height: ${defaultTheme.remify(40)};

  transition: 0.3s ease;
`;

const Tab = styled.li`
  display: inline-flex;
  align-items: center;

  padding: 0 ${defaultTheme.remify(16)};

  line-height: ${defaultTheme.remify(20)};
  margin-bottom: ${defaultTheme.remify(12)};

  border-right: 4px solid white;
  border-left: ${({ active }) => (active ? `4px solid ${color.purple}` : '4px solid white')};

  color: ${({ active }) => (active ? `${color.purple}` : `${color.charcoal}`)};
  font-size: ${defaultTheme.remify(18)};
  &:hover {
    border-left: 4px solid ${color.purple};
    color: ${color.purple};
  }
`;

const TabLink = styled.a`
  color: inherit;
  text-decoration: none;
`;

const HighlightedLink = styled(TabLink)`
  color: #ed1f7a;
`;

const HighlightedTab = styled(Tab)`
  border-left: ${({ active }) => (active ? '4px solid #ed1f7a' : '4px solid white')};

  &:hover {
    border-left: 4px solid #ed1f7a;
  }
`;

// eslint-disable-next-line max-len
const createHandleClick = (setHardTabMenuActive, hardTabMenuActive, menuRef) => ({ target }: MouseEvent) => {
  const active = !!menuRef.current && menuRef.current.contains(target) && !hardTabMenuActive;
  setHardTabMenuActive(active);
};

const createListenersAndDestructors = (target, handleClick) => () => {
  target.addEventListener('mousedown', handleClick);
  // Return a function that removes the event from the document
  return () => {
    target.removeEventListener('mousedown', handleClick);
  };
};

const DropDownTabMenu = ({
  tabs, me,
}: Props) => {
  const [softTabMenuActive, setSoftTabMenuActive] = useState<boolean>(false);
  const [hardTabMenuActive, setHardTabMenuActive] = useState<boolean>(false);
  const menuRef = React.createRef();

  // Create the click handler
  const handleClick = createHandleClick(setHardTabMenuActive, hardTabMenuActive, menuRef);
  // Attach the click handler to the window

  useEffect(() => {
    if (typeof window !== 'undefined') {
      createListenersAndDestructors(window, handleClick);
    }
  }, [handleClick]);

  return (
    <DropDownMenu
      ref={menuRef}
      onMouseEnter={() => setSoftTabMenuActive(true)}
      onMouseLeave={() => setSoftTabMenuActive(false)}
      onClick={handleClick}
    >
      <MobileLogo />
      <TabChevron
        active={hardTabMenuActive}
        dataGtmEventType={`${(hardTabMenuActive) ? 'close' : 'open'}-tab-menu-click`}
        dataGtmEventContext="HeaderLeft-Chevron"
      />
      {hardTabMenuActive && (
      <Nav>
        <TabMenu active={softTabMenuActive || hardTabMenuActive}>
          {tabs.map(({ text, href, active }) => (
            <Tab active={active} key={text}>
              <TabLink
                href={href}
                data-gtm-event-type={`${text}-click`}
                data-gtm-event-context="HeaderButtons"
              >
                {text}
              </TabLink>
            </Tab>
          ))}
          { !me && (
            <>
              <Tab>
                <TabLink
                  href="/login"
                  data-gtm-event-type="login-click"
                  data-gtm-event-context="HeaderButtons"
                >
                  Log In
                </TabLink>
              </Tab>
              <HighlightedTab>
                <HighlightedLink
                  href="/signup"
                  data-gtm-event-type="signup-click"
                  data-gtm-event-context="HeaderButtons"
                >
                  Sign up
                </HighlightedLink>
              </HighlightedTab>
            </>
          )}
        </TabMenu>
      </Nav>
      )}
    </DropDownMenu>
  );
};

export default DropDownTabMenu;
