import React, { ReactElement, ReactNode } from 'react';
import { Menu } from '@nova-hf/ui';
import { MenuProps } from '@nova-hf/ui/umd/ts/src/menu/Menu';
import { MenuItemProps } from '@nova-hf/ui/umd/ts/src/menu/MenuItem';
import { inject } from 'mobx-react';
import getConfig from 'next/config';
import Link from 'next/link';
import { useRouter } from 'next/router';
import Authentication from 'store/authentication';
import Profiles from 'store/profiles';
import UI from 'store/ui';
import { useCustomerProfilesQuery } from 'typings/graphql';
import { useTranslation } from 'utils/i18n';

type DropDownItem = Omit<MenuItemProps, 'color'>;
type DropdownItems = DropDownItem[];

const { publicRuntimeConfig } = getConfig();
const authServerUrl = publicRuntimeConfig.AUTHENTICATION_SERVER_URL;

interface UserMenuProps {
  authentication?: Authentication;
  profiles?: Profiles;
  children: ReactNode;
  ui: UI;
}

const UserMenu = ({ authentication, profiles, children, ui }: UserMenuProps) => {
  const { t } = useTranslation('common');
  const router = useRouter();

  if (!authentication || !profiles) return null;

  const {
    accountInput: { ssn },
  } = authentication;

  const onLogout = () => {
    authentication.logout();
  };

  const { data, loading } = useCustomerProfilesQuery({
    // use loggedInUserSsn to get users ssn not the current profile ssn
    variables: { accountInput: { ssn: authentication.loggedInUserSsn } },
    skip: !authentication.loggedInUserSsn,
  });

  const switchProfile = (ssn: string) => {
    authentication.logout();
    window.location.href = `${authServerUrl}/profiles/select?id=${ssn}&returnUrl=${`${window.location.protocol}//${window.location.host}`}`;
  };

  const registeredProfileItems: DropdownItems = [
    {
      hasSeparator: authentication.isStaff,
      text: t('navigation.main.services'),
      href: `/${ssn}/thjonustur`,
      isActive: router?.pathname.includes('thjonustur') || router?.pathname.includes('thjonusta'),
      wrapper: (child) => (
        <Link href={`/${ssn}/thjonustur`} passHref legacyBehavior>
          {child}
        </Link>
      ),
    },
    {
      text: t('navigation.main.invoices'),
      href: `/${ssn}/reikningar`,
      isActive: router?.pathname.includes('reikningar'),
      wrapper: (child) => (
        <Link href={`/${ssn}/reikningar`} passHref legacyBehavior>
          {child}
        </Link>
      ),
    },
    {
      text: t('navigation.main.transactions'),
      href: `/${ssn}/hreyfingalisti`,
      isActive: router?.pathname.includes('hreyfingalisti'),
      wrapper: (child) => (
        <Link href={`/${ssn}/hreyfingalisti`} passHref legacyBehavior>
          {child}
        </Link>
      ),
    },
    {
      text: t('navigation.main.settings'),
      href: `/${ssn}/stillingar`,
      isActive: router?.pathname.includes('stillingar'),
      wrapper: (child) => (
        <Link href={`/${ssn}/stillingar`} passHref legacyBehavior>
          {child}
        </Link>
      ),
    },
  ];

  const staffActionItems: DropdownItems = [
    {
      hasSeparator: true,
      separatorText: {
        text: t('navigation.userMenu.actionTitle'),
      },
      isBold: true,
      text: t('navigation.userMenu.switchCustomer'),
      href: '/staff',
      wrapper: (child) => (
        <Link href="/staff" passHref legacyBehavior>
          {child}
        </Link>
      ),
    },
    {
      isBold: true,
      text: 'Stilla sölustað',
      onClick: () => ui?.setShowSalesLocationPrompt(true),
    },
  ];

  const staffCustomerItems: DropdownItems =
    authentication.isStaff && data?.me?.ssn
      ? [
          {
            separatorText: {
              text: t('navigation.userMenu.customerTitle'),
              isHighlighted: true,
            },
            isBold: true,
            text: data.me.name ? data.me.name : '',
            onClick: onLogout,
            href: `/${data.me.ssn}`,
            wrapper: (child) => (
              <Link href={`/${data?.me?.ssn}`} passHref legacyBehavior>
                {child}
              </Link>
            ),
          },
        ]
      : [];

  const customerProfileItems =
    !loading && data?.me?.customerProfiles
      ? data?.me?.customerProfiles
          .filter((p) => p.nationalId !== ssn)
          .map(
            (p, i) =>
              ({
                hasSeparator: i < 1,
                separatorText:
                  i < 1
                    ? {
                        text: t('navigation.userMenu.switchUser'),
                      }
                    : undefined,
                text: p.name,
                href: authentication.isStaff ? `/${p.nationalId}/thjonustur` : '',
                onClick: () => switchProfile(p.nationalId),
                isBold: true,
                icon: 'arrowRight',
              }) as DropDownItem,
          )
      : [];

  const items = [
    ...staffCustomerItems,
    ...(profiles.isRegistered && ssn ? registeredProfileItems : []),
    ...customerProfileItems,
    ...(authentication.isStaff ? staffActionItems : []),
    {
      hasSeparator: true,
      text: t('logOut'),
      onClick: onLogout,
      href: `${authServerUrl}/account/logout`,
    },
  ];

  const args: Omit<MenuProps, 'disclosure'> = {
    color: 'pink',
    label: 'User menu',
    items: items,
  };
  return <Menu {...args} disclosure={children as ReactElement} />;
};

export default inject('authentication', 'profiles', 'ui')(UserMenu);
