import React from 'react';
import { Navbar } from '@nova-hf/ui';
import { setUser } from '@sentry/browser';
import { getFeatureFlags } from 'beta/components/feature-flags/FeatureFlags';
import Authentication from 'beta/store/authentication';
import UI from 'beta/store/ui';
import { getFirstName } from 'beta/utils/helpers';
import { useTranslation } from 'beta/utils/i18n';
import { inject, observer } from 'mobx-react';
import Link from 'next/link';
import { useRouter } from 'next/router';
import { Customer, useCustomerNameQuery } from 'typings/graphql';

import UserMenu from '../user-menu/UserMenu';

const featureFlags = getFeatureFlags();
const isBetaFlagActive = featureFlags['beta'];

const EXTERNAL_NAVBAR_LINKS = (
  isStaff?: boolean,
): Record<'fylltann' | '2f1' | 'search', string> => {
  return {
    fylltann: isStaff
      ? 'https://www.nova.is/audkenning/staff?redirect=/fylltann'
      : 'https://www.nova.is/fylltann',
    '2f1': 'https://www.nova.is/dansgolfid/2fyrir1',
    search: 'https://www.nova.is',
  };
};

const setSentryUser = (customer: Omit<Customer, 'created' | 'status'>) => {
  setUser({
    id: customer.id ?? '',
    username: customer.name ?? '',
    email: customer.email ?? '',
  });
};

type NavbarContainerProps = {
  authentication?: Authentication;
  ui?: UI;
};
const NavbarContainer = ({ authentication, ui }: NavbarContainerProps) => {
  const { t } = useTranslation('common');
  const isStaff = !!authentication?.isStaff;
  const customerId = authentication?.customerId;
  const router = useRouter();

  const { data, loading, error } = useCustomerNameQuery({
    variables: {
      input: {
        id: customerId ?? '',
      },
    },
  });

  if (data?.customer) {
    const user: Omit<Customer, 'created' | 'status'> = data.customer;
    setSentryUser(user);
  }

  const statusText = (): string => {
    if (data?.customer?.nickname) {
      const nickname: string = data.customer.nickname;
      return getFirstName(nickname);
    }
    if (data?.customer?.name) {
      const name: string = data.customer.name;
      return getFirstName(name);
    }
    if (data?.customer?.email) return data.customer.email.split('@')[0];
    return '...';
  };

  if (error || !data) return null;

  return (
    <Navbar
      zIndex={ui?.isMegaMenuOpen ? 3 : 1}
      isInverted={!!ui?.isHeaderInverted || !!ui?.isMegaMenuOpen}
      onMenuClick={() => ui?.setIsMegaMenuOpen(!ui.isMegaMenuOpen)}
      logo={{
        wrapper: (link) => (
          <Link href={'/'} passHref legacyBehavior>
            {link}
          </Link>
        ),
        hideOn: ['md', 'lg', 'xl'],
      }}
      menuIsOpen={ui?.isMegaMenuOpen}
      navbarItem={[
        {
          id: 'search',
          icon: 'search',
          tooltipText: t('navbar.leit'),
          onClick: () => {
            ui?.setIsMegaMenuOpen(false);
            if (isStaff) {
              isBetaFlagActive ? router.push('/beta/staff') : (window.location.href = '/staff');
            } else if (!isStaff) {
              window.open(EXTERNAL_NAVBAR_LINKS().search, '_blank');
            }
          },
        },
        {
          id: 'twoForOne',
          icon: 'twoForOne',
          tooltipText: t('navbar.2f1'),
          openInNewTab: true,
          href: EXTERNAL_NAVBAR_LINKS()['2f1'],
        },
        {
          id: 'refill',
          icon: 'refill',
          tooltipText: t('navbar.fylltann'),
          openInNewTab: true,
          href: EXTERNAL_NAVBAR_LINKS(isStaff).fylltann,
        },
      ]}
      navbarStatus={{
        isStaff: isStaff,
        isLoggedIn: true,
        text: loading ? '...' : statusText(),
        onClick: () => {},
        wrapper: (child) => <UserMenu>{child}</UserMenu>,
      }}
    />
  );
};

export default inject('ui', 'authentication')(observer(NavbarContainer));
