// @flow
import type { Node } from 'react';
import * as PAGES from 'constants/pages';
import * as ICONS from 'constants/icons';
import React from 'react';
import Button from 'component/button';
import StickyBox from 'react-sticky-box/dist/esnext';
import classnames from 'classnames';
import NotificationBubble from 'component/notificationBubble';

const ESCAPE_KEY_CODE = 27;
const BACKSLASH_KEY_CODE = 220;
const TOP_LEVEL_LINKS: Array<{
  label: string,
  navigate: string,
  icon: string,
  extra?: Node,
  hideForUnauth?: boolean,
}> = [
  {
    label: __('Home'),
    navigate: `/`,
    icon: ICONS.HOME,
  },
  {
    label: __('Following'),
    navigate: `/$/${PAGES.CHANNELS_FOLLOWING}`,
    icon: ICONS.SUBSCRIBE,
  },
  {
    label: __('Your Tags'),
    navigate: `/$/${PAGES.TAGS_FOLLOWING}`,
    icon: ICONS.TAG,
    hideForUnauth: true,
  },
  {
    label: __('Discover'),
    navigate: `/$/${PAGES.DISCOVER}`,
    icon: ICONS.DISCOVER,
  },
  {
    label: __('Purchased'),
    navigate: `/$/${PAGES.LIBRARY}`,
    icon: ICONS.PURCHASED,
    hideForUnauth: true,
  },
];

const ABSOLUTE_LINKS: Array<{
  label: string,
  navigate: string,
  icon: string,
  extra?: Node,
  hideForUnauth?: boolean,
}> = [
  {
    label: __('Upload'),
    navigate: `/$/${PAGES.UPLOAD}`,
    icon: ICONS.PUBLISH,
  },
  {
    label: __('New Channel'),
    navigate: `/$/${PAGES.CHANNEL_NEW}`,
    icon: ICONS.CHANNEL,
  },
  {
    label: __('Uploads'),
    navigate: `/$/${PAGES.UPLOADS}`,
    icon: ICONS.PUBLISH,
    hideForUnauth: true,
  },

  {
    label: __('Channels'),
    navigate: `/$/${PAGES.CHANNELS}`,
    icon: ICONS.CHANNEL,
    hideForUnauth: true,
  },
  {
    label: __('Creator Analytics'),
    navigate: `/$/${PAGES.CREATOR_ANALYTICS}`,
    icon: ICONS.ANALYTICS,
  },
  {
    label: __('Notifications'),
    navigate: `/$/${PAGES.NOTIFICATIONS}`,
    icon: ICONS.NOTIFICATION,
    extra: <NotificationBubble />,
    hideForUnauth: true,
  },
  {
    label: __('Rewards'),
    navigate: `/$/${PAGES.REWARDS}`,
    icon: ICONS.REWARDS,
    hideForUnauth: true,
  },
  {
    label: __('Invites'),
    navigate: `/$/${PAGES.INVITES}`,
    icon: ICONS.INVITE,
    hideForUnauth: true,
  },
  {
    label: __('Settings'),
    navigate: `/$/${PAGES.SETTINGS}`,
    icon: ICONS.SETTINGS,
    hideForUnauth: true,
  },
  {
    label: __('Help'),
    navigate: `/$/${PAGES.HELP}`,
    icon: ICONS.HELP,
    hideForUnauth: true,
  },
];

type Props = {
  subscriptions: Array<Subscription>,
  email: ?string,
  uploadCount: number,
  doSignOut: () => void,
  sidebarOpen: boolean,
  setSidebarOpen: boolean => void,
  isMediumScreen: boolean,
  isOnFilePage: boolean,
  unreadCount: number,
  purchaseSuccess: boolean,
  doClearPurchasedUriSuccess: () => void,
};

function SideNavigation(props: Props) {
  const {
    subscriptions,
    // doSignOut,
    email,
    purchaseSuccess,
    doClearPurchasedUriSuccess,
    sidebarOpen,
    setSidebarOpen,
    isMediumScreen,
    isOnFilePage,
    unreadCount,
  } = props;
  const isAuthenticated = Boolean(email);
  const [pulseLibrary, setPulseLibrary] = React.useState(false);
  const isPersonalized = !IS_WEB || isAuthenticated;
  const isAbsolute = isOnFilePage || isMediumScreen;

  React.useEffect(() => {
    if (purchaseSuccess) {
      setPulseLibrary(true);

      let timeout = setTimeout(() => {
        setPulseLibrary(false);
        doClearPurchasedUriSuccess();
      }, 2500);

      return () => clearTimeout(timeout);
    }
  }, [setPulseLibrary, purchaseSuccess, doClearPurchasedUriSuccess]);

  React.useEffect(() => {
    function handleKeydown(e: SyntheticKeyboardEvent<*>) {
      if (e.keyCode === ESCAPE_KEY_CODE && isAbsolute) {
        setSidebarOpen(false);
      } else if (e.keyCode === BACKSLASH_KEY_CODE) {
        const hasActiveInput = document.querySelector('input:focus');
        if (!hasActiveInput) {
          setSidebarOpen(!sidebarOpen);
        }
      }
    }

    window.addEventListener('keydown', handleKeydown);

    return () => window.removeEventListener('keydown', handleKeydown);
  }, [sidebarOpen, setSidebarOpen, isAbsolute]);

  const Wrapper = ({ children }: any) =>
    !isOnFilePage && !isMediumScreen ? (
      <StickyBox offsetTop={100} offsetBottom={20}>
        {children}
      </StickyBox>
    ) : (
      children
    );

  return (
    <Wrapper>
      {!isOnFilePage && (
        <nav className={classnames('navigation', { 'navigation--micro': !sidebarOpen || isMediumScreen })}>
          <ul className={classnames('navigation-links--relative', { 'navigation-links--micro': !sidebarOpen })}>
            {TOP_LEVEL_LINKS.map(linkProps =>
              !email && linkProps.hideForUnauth && IS_WEB ? null : (
                <li key={linkProps.navigate}>
                  <Button
                    {...linkProps}
                    icon={pulseLibrary && linkProps.icon === ICONS.LIBRARY ? ICONS.PURCHASED : linkProps.icon}
                    className={classnames('navigation-link', {
                      'navigation-link--pulse': linkProps.icon === ICONS.LIBRARY && pulseLibrary,
                      'navigation-link--extra': linkProps.icon === ICONS.NOTIFICATION && unreadCount > 0,
                    })}
                    activeClass="navigation-link--active"
                  />
                  {linkProps.extra}
                </li>
              )
            )}
          </ul>

          {sidebarOpen && isPersonalized && subscriptions && subscriptions.length > 0 && (
            <ul className="navigation__secondary navigation-links--relative navigation-links--small">
              {subscriptions.map(({ uri, channelName }, index) => (
                <li key={uri} className="navigation-link__wrapper">
                  <Button
                    navigate={uri}
                    label={channelName}
                    className="navigation-link"
                    activeClass="navigation-link--active"
                  />
                </li>
              ))}
            </ul>
          )}
        </nav>
      )}

      {(isOnFilePage || isMediumScreen) && sidebarOpen && (
        <>
          <nav className={classnames('navigation--filepage')}>
            <ul className="navigation-links--absolute">
              {TOP_LEVEL_LINKS.map(linkProps => (
                <li key={linkProps.navigate}>
                  <Button
                    {...linkProps}
                    icon={pulseLibrary && linkProps.icon === ICONS.LIBRARY ? ICONS.PURCHASED : linkProps.icon}
                    className={classnames('navigation-link', {
                      'navigation-link--pulse': linkProps.icon === ICONS.LIBRARY && pulseLibrary,
                      'navigation-link--extra': linkProps.icon === ICONS.NOTIFICATION && unreadCount > 0,
                    })}
                    activeClass="navigation-link--active"
                  />
                  {linkProps.extra}
                </li>
              ))}
            </ul>
            <ul className="navigation-links--absolute">
              {ABSOLUTE_LINKS.map(linkProps => (
                <li key={linkProps.navigate}>
                  <Button {...linkProps} className="navigation-link" activeClass="navigation-link--active" />
                  {linkProps.extra}
                </li>
              ))}
            </ul>
            {isPersonalized && subscriptions && subscriptions.length > 0 && (
              <ul className="navigation__secondary navigation-links--small">
                {subscriptions.map(({ uri, channelName }, index) => (
                  <li key={uri} className="navigation-link__wrapper">
                    <Button
                      navigate={uri}
                      label={channelName}
                      className="navigation-link"
                      activeClass="navigation-link--active"
                    />
                  </li>
                ))}
              </ul>
            )}
          </nav>
          <div className="navigation__overlay" onClick={() => setSidebarOpen(false)} />
        </>
      )}
    </Wrapper>
  );
}

export default SideNavigation;
