import React, { ReactNode } from 'react';
import { Box, IconButton, Menu, SideMenu, Text } from '@nova-hf/ui';
import { LinkProps } from '@nova-hf/ui/umd/ts/src/sidemenu/SideMenuLink';
import Authentication from 'beta/store/authentication';
import { inject, observer } from 'mobx-react';
import Link from 'next/link';
import { NextRouter, useRouter } from 'next/router';
import { useCustomerNameQuery, useWalletCardsRegisteredQuery } from 'typings/graphql';
import { staffMenuLinksFirstLevel } from 'utils/staffMenuLinks';

const mainLinks = (
  nationalId: string,
  customerId: string,
  router: NextRouter,
): Array<Omit<LinkProps, 'isStaffMenuOpen'>> => {
  return [
    /*{
     id: 'overview',
     icon: 'home',
     text: 'Yfirlit',
     color: 'pink',
     isLink: true,
     isActive: router?.pathname.includes('yfirlit'),
     wrapper: (link) => (
       <Link href={`/beta/${customerId}/yfirlit`} passHref>
         {link}
       </Link>
     ),
   }, */
    {
      id: 'services',
      icon: 'mobile',
      text: 'Þjónustur',
      color: 'pink',
      isLink: true,
      isActive: false,
      onClick: () => (window.location.href = `/${nationalId}/thjonustur`), // will be beta þjonustur
    },
    {
      id: 'invoices',
      icon: 'creditcard',
      text: 'Reikningar',
      color: 'blue',
      isLink: true,
      isActive: router?.pathname.includes('reikningar'),
      onClick: () => (window.location.href = `/${nationalId}/reikningar`), // will be beta reikningar
    },
    {
      id: 'sagan',
      icon: 'selfie',
      text: 'Sagan',
      color: 'green',
      isLink: true,
      isActive: router?.pathname.includes('sagan'),
      onClick: () => router?.push(`/beta/${customerId}/sagan`),
    },
    {
      id: 'transactionList',
      icon: 'history',
      text: 'Hreyfingalisti',
      color: 'purple',
      isLink: true,
      isActive: router?.pathname.includes('hreyfingalisti'),
      onClick: () => (window.location.href = `/${nationalId}/hreyfingalisti`), // will be beta hreyfingar
    },
    /*
  {
    id: 'invoices',
    icon: 'creditcard',
    text: 'Reikningar',
    color: 'blue',
    isLink: true,
    isActive: router?.pathname.includes('reikningar'),
    wrapper: (link) => (
      <Link href={`/beta/${customerId}/reikningar`} passHref>
        {link}
      </Link>
    ),
  },
  {
    id: 'transactionList',
    icon: 'history',
    text: 'Hreyfingalisti',
    color: 'purple',
    isLink: true,
    isActive: router?.pathname.includes('hreyfingalisti'),
    wrapper: (link) => (
      <Link href={`/beta/${customerId}/hreyfingalisti`} passHref>
        {link}
      </Link>
    ),
  },
    */
  ].filter(Boolean) as Array<Omit<LinkProps, 'isStaffMenuOpen'>>;
};

const secondaryLinks = (
  ssn: string,
  customerId: string,
  hasRegisteredCards: boolean,
  isCompany: boolean,
  isStaff: boolean,
  router: NextRouter,
): Array<Omit<LinkProps, 'isStaffMenuOpen'>> => {
  const generalLinks: Array<Omit<LinkProps, 'isStaffMenuOpen'>> = [
    {
      id: 'repairs',
      icon: 'return',
      text: 'Viðgerðir',
      color: 'green',
      isLink: true,
      isActive: router?.pathname.includes('vidgerdir'),
      onClick: () => (window.location.href = `/${ssn}/vidgerdir`),
    },
    {
      id: 'settings',
      icon: 'settings',
      text: 'Stillingar',
      color: 'pink',
      isLink: true,
      isActive: router?.pathname.includes('stillingar') && !router?.pathname.includes('tengilidir'),
      onClick: () => (window.location.href = `/${ssn}/stillingar`),
    },
    {
      id: 'contacts',
      icon: 'userCircle',
      text: 'Tengiliðir',
      color: 'pink',
      isLink: true,
      isActive: router?.pathname.includes('stillingar/tengilidir'),
      onClick: () => (window.location.href = `/${ssn}/stillingar/tengilidir`),
    } as Omit<LinkProps, 'isStaffMenuOpen'>,
    {
      id: 'hradleid',
      icon: 'transfer',
      text: 'Fjöldaaðgerðir',
      color: 'pink',
      isLink: true,
      isActive: router?.pathname.includes('thjonustur'),
      wrapper: () => (
        <Menu
          color="pink"
          label="MultiLinkMenu"
          items={[
            {
              text: 'Ljósleiðari',
              onClick: () => router.push(`/beta/${router?.query?.customerId}/thjonustur`),
            },
            {
              text: 'Farsími',
              onClick: () => (window.location.href = `/${ssn}/fjoldaskraning`),
            },
          ]}
          disclosure={
            <Box alignItems="center" display="flex" flexDirection="row" marginLeft={-1}>
              <IconButton color="grey600" icon="transfer" hiddenButtonText="More button" />
              <Text color="grey600" variant="eyebrowLarge">
                Fjöldaaðgerðir
              </Text>
            </Box>
          }
        />
      ),
    },
    ...(isCompany
      ? [
          {
            id: 'deildir',
            icon: 'company',
            text: 'Deildir',
            color: 'pink',
            isLink: true,
            isActive: router?.pathname.includes('deildir'),
            wrapper: (link: React.ReactNode) => (
              <Link href={`/beta/${customerId}/deildir`} passHref legacyBehavior>
                {link}
              </Link>
            ),
          },
        ]
      : []),
  ].filter(Boolean) as Array<Omit<LinkProps, 'isStaffMenuOpen'>>;

  return hasRegisteredCards
    ? [
        {
          id: 'felagakort',
          icon: 'wallet',
          text: 'Félagakort',
          color: 'ocean',
          isLink: true,
          isActive: router?.pathname.includes('felagakort'),
          wrapper: (link) => (
            <Link href={`/${ssn}/felagakort/kort`} passHref legacyBehavior>
              {link}
            </Link>
          ),
        },
        ...generalLinks,
      ]
    : generalLinks;
};

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

const SideMenuContainer = ({ authentication, children }: SideMenuContainerProps) => {
  const router = useRouter();

  const username = authentication?.username;
  const isStaff = authentication?.isStaff;

  const { data: registeredCardsData, loading: registeredCardsLoading } =
    useWalletCardsRegisteredQuery({
      skip: isStaff,
    });

  const firstName = username?.split(' ')[0];

  const { data, error } = useCustomerNameQuery({
    variables: {
      input: {
        id: (router.query.customerId as string) ?? '',
      },
    },
  });

  if (!data || !data.customer?.id || error) return null;

  const hasRegisteredCards: boolean =
    !registeredCardsLoading && !!registeredCardsData?.walletCardsRegistered?.registered?.length;

  const isCompany = data?.customer?.isCompany;

  return (
    <Box
      position={{ sm: 'absolute', md: 'relative' }}
      marginTop={{ sm: 9, md: 0 }}
      left={0}
      right={0}
      top={0}
      zIndex="sidemenu"
    >
      <SideMenu
        isStaff={isStaff}
        staffName={firstName}
        logo={{
          href: '/',
          wrapper: (link) => (
            <Link
              href={'/'}
              passHref
              onClick={(event) => {
                event.preventDefault();
                window.location.href = '/';
              }}
            >
              {link}
            </Link>
          ),
        }}
        mainLinks={mainLinks(data?.customer?.nationalId ?? '', data?.customer?.id ?? '', router)}
        secondaryLinks={secondaryLinks(
          data?.customer?.nationalId ?? '',
          data?.customer?.id,
          hasRegisteredCards,
          isCompany ?? false,
          isStaff ?? false,
          router,
        )}
        staffMenuLinks={staffMenuLinksFirstLevel(data?.customer?.nationalId ?? '')}
        {...(isStaff && { customerLabel: 'Viðskiptavinur' })}
        {...(isStaff &&
          data?.customer && {
            customer: {
              name: data?.customer?.name ?? '',
              ssn: data?.customer?.nationalId ?? '',
              /*address:
               `${data?.me?.userProfile?.streetAddress}, ${data?.me?.userProfile?.postalCode} ${data?.me?.userProfile?.city}` ??
               '',*/
              email: data?.customer.email ?? '',
            },
          })}
      >
        {children}
      </SideMenu>
    </Box>
  );
};

export default inject('authentication')(observer(SideMenuContainer));
