import { memo, useCallback, useMemo } from 'react';
import dynamic from 'next/dynamic';

import type { MappedUser } from '~/src/lib/songwhipApi/users/types';
import type { ClickableOnClick } from '../../Clickable';
import type { SideNavItem } from '../types';

import Box from '~/src/components/Box';
import FadeOnMount from '~/src/components/FadeOnMount';
import PersonIcon from '~/src/components/Icon/PersonIcon';
import useZendesk from '~/src/hooks/useZendesk';
import { useI18n } from '~/src/lib/i18n';
import { useAppRouter } from '~/src/lib/router2';
import ChartIcon from '../../Icon/ChartIcon';
import LinkIcon from '../../Icon/LinkIcon';
import MagicWandIcon from '../../Icon/MagicWand';
import SideNavInternal from '../SideNavInternal';

const OrchardAppSwitcherDynamic = dynamic(
  () => import('./OrchardAppSwitcher'),
  { ssr: false }
);

const OrchardSideNav = memo<{
  onCloseClick: () => void;
  onItemClick: () => void;
  isVisible: boolean;
  user: MappedUser;
}>(({ user, onItemClick, ...sideNavInternalProps }) => {
  const { t } = useI18n('app');

  const router = useAppRouter();
  const zendesk = useZendesk();

  const onItemClickInternal: ClickableOnClick<unknown> = ({ event, href }) => {
    const { origin, pathname } = new URL(href ?? '/', location.origin);

    // external links: let <Link2> handle navigation via window.location
    if (!href || origin !== location.origin) {
      onItemClick();
      return;
    }

    event.preventDefault();
    const persistedQuery = router.getPersistedQuery(pathname);

    router.push(href, { asQuery: persistedQuery, routerQuery: persistedQuery });
    onItemClick();
  };

  return (
    // We're using internal <FadeOnMount> here so that
    // when this is lazy-loaded it still fades in. Wrapping
    // a lazy/dynamic component in <FadeOnMount> will fade
    // in an empty wrapper component before the chunk is fetched.
    <FadeOnMount>
      <div style={{ height: '100%' }}>
        <SideNavInternal
          {...sideNavInternalProps}
          homePath="/create"
          user={user}
          onItemClick={onItemClickInternal}
          primaryItems={[
            {
              key: 'catalog',
              text: t('sideNav.catalog'),
              href: '/catalog',
              Icon: LinkIcon,
            },
            {
              key: 'create',
              text: t('sideNav.makeALink'),
              href: '/create',
              Icon: MagicWandIcon,
            },
            {
              key: 'dashboard',
              text: t('sideNav.analytics'),
              href: '/dashboard',
              Icon: ChartIcon,
            },
            {
              key: 'account',
              text: t('sideNav.account'),
              href: '/account',
              Icon: PersonIcon,
            },
          ]}
          secondaryItems={useMemo((): SideNavItem[] => {
            return [
              // todo-2593 return this section one we redo the faqs
              // {
              //   key: 'faq',
              //   text: t('sideNav.faqs'),
              //   href:
              //     user.orchardBrand === OrchardBrands.SME
              //       ? '/faq/sme'
              //       : '/faq/orchard',
              // },
              {
                key: 'support',
                text: 'Help',
                testId: 'zendeskHelp',

                onClick: async () => {
                  zendesk.open();
                },
              },
              ...(user.isAdmin
                ? [
                    {
                      key: 'tools',
                      text: 'Tools',
                      href: '/admin/tools',
                    },
                  ]
                : []),
            ];
          }, [])}
          renderAfter={useCallback(({ hasBeenVisible }) => {
            return (
              <>
                <Box height="5.4em" style={{ borderTop: 'solid 1px #333' }}>
                  {hasBeenVisible && (
                    <FadeOnMount>
                      <Box fullHeight>
                        <OrchardAppSwitcherDynamic
                          userId={user.id}
                          orchardBrand={user?.orchardBrand}
                        />
                      </Box>
                    </FadeOnMount>
                  )}
                </Box>
              </>
            );
          }, [])}
        />
      </div>
    </FadeOnMount>
  );
});

export default OrchardSideNav;
