// @flow
import React, { useState, useEffect } from 'react';
import styled from 'styled-components';

import type { Link, Member } from '../../../types';

import ApoliticalLogo from '../../Atom/ApoliticalLogo/ApoliticalLogo';
import DropDownProfileMenu from '../DropDownProfileMenu';
import DropDownTabMenu from '../DropDownTabMenu';

import Button from '../../Atom/Button/Button';
import ModalSearch from '../ModalSearch';
import SearchForm from '../../Molecule/SearchForm/SearchForm';
import defaultTheme from '../../../Theme/ApoliticalBrand';

const { color } = defaultTheme;

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

const headerSize = {
  fullWidth: {
    height: 80,
    breakpoint: 1000,
  },
  mobileWidth: {
    height: 60,
    breakpoint: 800,
  },
};

const HeaderSpacer = styled.div`
  width: 100%;
  height: ${defaultTheme.remify(headerSize.mobileWidth.height)};
  @media only screen and (min-width: ${headerSize.mobileWidth.breakpoint}px) {
    height: ${defaultTheme.remify(headerSize.fullWidth.height)};
  }
`;

const HeaderContainer = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;

  height: ${defaultTheme.remify(headerSize.mobileWidth.height)};
  width: 100%;

  position: fixed;
  top: ${({ active }) => (active ? '0' : defaultTheme.remify(-100))};
  z-index: 9999;

  background: white;

  transition: 0.3s ease;
  @media only screen and (min-width: ${headerSize.mobileWidth.breakpoint}px) {
    height: ${defaultTheme.remify(headerSize.fullWidth.height)};
  }
`;

const HeaderInnerWrap = styled.div`
  display: flex;
  width: 100%;
  max-width: ${defaultTheme.remify(1440)};
  padding: 0 ${defaultTheme.remify(20)};
  margin: 0 auto;
`;

const Column = styled.div`
  display: flex;
  align-items: center;
  height: ${defaultTheme.remify(headerSize.fullWidth.height)};
`;

const LeftColumn = styled(Column)`
  flex: 1 1 auto;
`;

const RightColumn = styled(Column)`
`;

const TabColumn = styled(Column)`
  display: none;
  @media only screen and (min-width: ${headerSize.mobileWidth.breakpoint}px) {
    display: flex;
  }
`;

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

const Tabs = styled.ul`
  display: flex;
`;

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

  height: ${defaultTheme.remify(headerSize.fullWidth.height - 2)};
  padding: 0 ${defaultTheme.remify(18)};

  border-top: 1px solid white;
  border-bottom: ${({ active }) => (active ? `1px solid ${color.purple}` : '1px solid white')};

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

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

const FullSearchBar = styled(SearchForm)`
  display: none;
  height: 100%;
  margin: 0 ${defaultTheme.remify(20)};
  flex-grow: 1;
  @media only screen and (min-width: ${headerSize.fullWidth.breakpoint}px) {
    display: flex;
  }
`;

const SearchModal = styled(ModalSearch)`
  display: flex;
  margin-left: ${defaultTheme.remify(30)};
  @media only screen and (min-width: ${headerSize.fullWidth.breakpoint}px) {
    display: none;
  }
`;

const PaddedLogo = styled(ApoliticalLogo)`
  padding: ${defaultTheme.remify(10)};
  display: none;
  @media only screen and (min-width: ${headerSize.mobileWidth.breakpoint}px) {
    display: flex;
  }
`;

const MobileTagLogo = styled.div`
  display: flex;
  height: ${defaultTheme.remify(60)};
  @media only screen and (min-width: ${headerSize.mobileWidth.breakpoint}px) {
    display: none;
  }
`;

const ButtonWrapper = styled.div`
@media only screen and (min-width: 800px){
  margin-right: 10px !important;
}
@media only screen and (max-width: ${headerSize.mobileWidth.breakpoint}px) {
  margin-right: 5px !important;
}
`;

const isActive = (pathname): boolean => (
  typeof window !== 'undefined'
  && window.location
  && window.location.pathname === pathname
);

const Header = (
  {
    me,
    profileMenuItems,
    isLoadingMember,
  }: Props,
) => {
  const [menuHack, setMenuHack] = useState<number>(0);
  const [showMainMenu, setShowMainMenu] = useState<boolean>(true);

  const tabs = [
    {
      text: 'My Home',
      href: '/home',
      active: (isActive('/') || isActive('/home')),
      gtmType: 'homepage-click',
    },
    {
      text: 'Events',
      href: '/events',
      active: isActive('/events'),
      gtmType: 'events-click',
    },
    {
      text: 'Courses',
      href: '/microcourses',
      active: isActive('/microcourses'),
      gtmType: 'microcourses-click',
    },
    {
      text: 'Q&A',
      href: '/questions-answers',
      active: isActive('/questions-answers'),
      gtmType: 'q-and-a-click',
    },
    {
      text: 'Articles',
      href: '/collections',
      active: (isActive('/solutions') || isActive('/collections')),
      gtmType: 'articles-click',
    },
  ];

  const menuRef = React.createRef();

  // Non state stuff we need to remember;
  let lastYPosition = typeof window !== 'undefined' ? window.scrollY : 0;
  let didScroll = false;

  const handleScroll = () => {
    didScroll = true;
  };
  const handleDidScroll = () => {
    if (didScroll && typeof window !== 'undefined') {
      const currentYPosition = window.scrollY;
      if (currentYPosition < headerSize.fullWidth.height) {
        lastYPosition = currentYPosition;
        setShowMainMenu(true);
        return;
      }

      const diff = lastYPosition - currentYPosition;
      if (diff > 10 || diff < -10) { // Buffer it a little, wait for 10px movement
        didScroll = false;
        lastYPosition = currentYPosition;
        // If Up
        if (diff > 0) {
          setShowMainMenu(true);
          return;
        }
        // Else Down
        setMenuHack(menuHack + 1); // This is a little hack to reset the profile menu
        setShowMainMenu(false);
      }
    }
  };

  // Attach the scroll event to the document
  useEffect(() => {
    const interval = setInterval(handleDidScroll, 250);
    if (typeof window !== 'undefined') {
      window.addEventListener('scroll', handleScroll);
    }
    // Return a function that removes the event from the document
    return () => {
      clearInterval(interval);
      if (typeof window !== 'undefined') {
        window.removeEventListener('scroll', handleScroll);
      }
    };
  });


  return (
    <HeaderSpacer>
      <HeaderContainer active={showMainMenu}>
        <HeaderInnerWrap>
          <LeftColumn>
            <PaddedLogo />
            <MobileTagLogo ref={menuRef}>
              <DropDownTabMenu
                key={menuHack}
                tabs={tabs || []}
                me={me}
              />
            </MobileTagLogo>
            {me && <SearchModal />}
            {me && <FullSearchBar />}
          </LeftColumn>
          <RightColumn>
            <TabColumn>
              <Nav>
                <Tabs>
                  {tabs && tabs.map(({
                    text, href, active, gtmType,
                  }) => (
                    <Tab active={active} key={text}>
                      <TabLink
                        href={href}
                        data-gtm-event-type={gtmType}
                        data-gtm-event-context="HeaderButtons"
                      >
                        {text}
                      </TabLink>
                    </Tab>
                  ))}
                </Tabs>
              </Nav>
            </TabColumn>
            <Column>
              {
                me && (
                  <DropDownProfileMenu
                    key={menuHack}
                    me={me}
                    profileMenuItems={profileMenuItems || []}
                  />
                )
              }
              {
                (!isLoadingMember && !me) && (
                  <>
                    <ButtonWrapper>
                      <Button
                        href="/signup?ref=header-banner"
                        data-gtm-event-type="signup-click"
                        data-gtm-event-context="HeaderButtons"
                        variant="primarySmall"
                      >
                        Sign Up
                      </Button>
                    </ButtonWrapper>
                    <Button
                      href="/user-onboarding/login"
                      data-gtm-event-type="login-click"
                      data-gtm-event-context="HeaderButtons"
                      variant="secondary"
                    >
                      Log In
                    </Button>
                  </>
                )
            }
            </Column>
          </RightColumn>
        </HeaderInnerWrap>
      </HeaderContainer>
    </HeaderSpacer>
  );
};

const profileMenuItems = [
  { text: 'My Profile', href: '/profile-ui/me' },
  { text: 'Settings & Privacy', href: '/profile-ui/me/manage-account' },
  { text: 'Log Out', href: '/user-onboarding/logout' },
];

Header.defaultProps = {
  profileMenuItems,
  isLoadingMember: false,
};

export default Header;
