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 Authentication from 'beta/store/authentication';
import { inject } from 'mobx-react';
import getConfig from 'next/config';
import Link from 'next/link';
import { useRouter } from 'next/router';
import { RoleType, useCustomerNameQuery, useCustomerRolesQuery } 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;

type UserMenuProps = {
  authentication?: Authentication;
  children: ReactNode;
};

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

  const loggedInCustomerId = authentication?.customerId?.toLowerCase();
  const customerIdViewed = (router.query.customerId as string)?.toLowerCase() ?? '';
  const isCustomerViewedMe = loggedInCustomerId === customerIdViewed;

  if (!authentication) return null;
  if (!customerIdViewed) return null;

  const { data, loading } = useCustomerRolesQuery({
    variables: {
      input: {
        id: loggedInCustomerId,
      },
    },
    skip: !loggedInCustomerId,
  });

  const { data: customerNameData, loading: customerNameLoading } = useCustomerNameQuery({
    variables: {
      input: {
        id: customerIdViewed ?? '',
      },
    },
    skip: !customerIdViewed,
  });

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

  const onSwitchProfile = (customerId: string, nationalId: string) => {
    authentication.logout();
    window.location.href = `${authServerUrl}/profiles/select?id=${nationalId}&returnUrl=${`${window.location.protocol}//${window.location.host}`}/beta/${customerId}/yfirlit`;
  };

  const customerNameSection: DropdownItems =
    authentication.isStaff && !isCustomerViewedMe && !customerNameLoading
      ? [
          {
            separatorText: {
              text: t('userMenu.customerTitle'),
              isHighlighted: true,
            },
            isBold: true,
            text:
              customerNameData?.customer?.name ??
              customerNameData?.customer?.nickname ??
              customerNameData?.customer?.email?.split('@')[0] ??
              '',
            onClick: onLogout,
            href: `/beta/${customerIdViewed}/yfirlit`,
            wrapper: (child) => (
              <Link href={`/beta/${customerIdViewed}/yfirlit`} passHref legacyBehavior>
                {child}
              </Link>
            ),
          },
        ]
      : [];

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

  const myPortalContacts =
    !loading && data?.customer?.roles && isCustomerViewedMe
      ? data.customer.roles
          .filter((role) => role.roleTypes.includes(RoleType.PortalContact))
          .map(
            (profile, i) =>
              ({
                hasSeparator: i < 1,
                separatorText:
                  i < 1
                    ? {
                        text: t('userMenu.myPortalContacts'),
                      }
                    : undefined,
                text: profile.subject.name,
                isBold: true,
                href: authentication.isStaff ? `/beta/${profile.subject.id}/yfirlit` : '',
                onClick: () =>
                  onSwitchProfile(profile.subject.id, profile.subject.nationalId ?? ''),
              }) as DropDownItem,
          )
      : [];

  const myProfile =
    !loading && !isCustomerViewedMe && !!loggedInCustomerId
      ? [
          {
            hasSeparator: true,
            separatorText: { text: t('userMenu.switchUser') },
            text: data?.customer?.name || t('userMenu.you'),
            isBold: true,
            href: `/beta/${loggedInCustomerId}/yfirlit`,
            onClick: () =>
              onSwitchProfile(loggedInCustomerId, (data?.customer?.nationalId as string) ?? ''),
          } as DropDownItem,
        ]
      : [];

  const switchCustomerSection: DropdownItems = authentication.isStaff
    ? [
        {
          hasSeparator: true,
          separatorText: {
            text: t('userMenu.actionTitle'),
          },
          isBold: true,
          text: t('userMenu.switchCustomer'),
          href: '/beta/staff',
        },
      ]
    : [];

  const dropdownItems = [
    ...customerNameSection,
    ...customerViewedNavigationItems,
    ...switchCustomerSection,
    ...myPortalContacts,
    ...myProfile,
    {
      hasSeparator: true,
      text: t('userMenu.logout'),
      onClick: onLogout,
      href: `${authServerUrl}/account/logout`,
    },
  ];

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

export default inject('authentication')(UserMenu);
