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

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

const DropDownMenu = styled.div`
  display: flex;
  align-items: center;

  height: 100%;
  width: ${defaultTheme.remify(60)};
  cursor: pointer;
`;

const ProfileMenu = styled.ul`
  height: ${({ active }) => (active ? 'unset' : '0')};
  width: ${defaultTheme.remify(212)};
  padding: ${({ active }) => {
    if (active) {
      return `${defaultTheme.remify(20)} ${defaultTheme.remify(30)}`;
    }
    return `0 ${defaultTheme.remify(30)}`;
  }};
  overflow: hidden;

  position: absolute;
  top: ${defaultTheme.remify(21)};
  right: 0;

  border-radius: 6px;
  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 ProfileMenuItem = styled.li`
  display: inline-block;
  width: 100%;

  color: ${({ active }) => (active ? `${defaultTheme.color.purple}` : `${defaultTheme.color.charcoal}`)};
  &:hover {
    color: ${defaultTheme.color.purple};
  }
`;

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

const SizeProfilePicture = styled(ProfilePicture)`
  height: ${defaultTheme.remify(32)};
  width: ${defaultTheme.remify(32)};

  position: relative;
  @media only screen and (min-width: 1000px) {
    height: ${defaultTheme.remify(40)};
    width: ${defaultTheme.remify(40)};
  }
`;

const Nav = styled.nav`
  position: relative;
`;

const createHandleClick = (setHardTabMenuActive, menuRef) => ({ target }: MouseEvent) => {
  const active = !!menuRef.current && menuRef.current.contains(target);
  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 DropDownProfileMenu = ({ me, profileMenuItems }: Props) => {
  const [softProfileMenuActive, setSoftProfileMenuActive] = useState<boolean>(false);
  const [hardProfileMenuActive, setHardProfileMenuActive] = useState<boolean>(false);
  const menuRef = React.createRef();
  const { name } = me;
  const src = me.image && me.image.thumbnail;

  // Create the click handler
  const handleClick = createHandleClick(setHardProfileMenuActive, menuRef);
  // Attach the click handler to the window
  useEffect(() => {
    if (typeof window !== 'undefined') {
      createListenersAndDestructors(window, handleClick);
    }
  }, [handleClick]); // Never changed

  return (
    <DropDownMenu
      ref={menuRef}
      className="gtm-trackable"
      onFocus={() => setSoftProfileMenuActive(true)}
      onBlur={() => setSoftProfileMenuActive(false)}
      onMouseEnter={() => setSoftProfileMenuActive(true)}
      onMouseLeave={() => setSoftProfileMenuActive(false)}
      onClick={handleClick}
      dataGtmEventType={`${(hardProfileMenuActive) ? 'close' : 'open'}-profile-menu-click`}
      dataGtmEventContext="HeaderRight-ProfileImage"
    >
      <SizeProfilePicture name={name} src={src} />
      <Nav>
        <ProfileMenu
          active={softProfileMenuActive || hardProfileMenuActive}
          aria-expanded={softProfileMenuActive || hardProfileMenuActive}
        >
          {profileMenuItems.map(({ text, href, active }) => (
            <ProfileMenuItem active={active} key={text}>
              <ProfileMenuLink href={href}>{text}</ProfileMenuLink>
            </ProfileMenuItem>
          ))}
        </ProfileMenu>
      </Nav>
    </DropDownMenu>
  );
};

export default DropDownProfileMenu;
