import React, { useEffect, useState } from 'react';
import { NetworkStatus } from '@apollo/client';
import {
  AttentionBanner,
  Box,
  Empty,
  Grid,
  GridItem,
  IconButton,
  MainButton,
  Menu,
  Pill,
  Text,
} from '@nova-hf/ui';
import { ErrorBanner } from 'beta/components/error/ErrorBanner';
import { CUSTOMER } from 'beta/graphql/queries/customer';
import Link from 'next/link';
import { useRouter } from 'next/router';
import { RoleType, useCustomerDelegatesQuery, useRemoveDelegateMutation } from 'typings/graphql';
import { formatPhone } from 'utils/helpers';
import { Trans, useTranslation } from 'utils/i18n';

import { StillingarLoader } from '../components/StillingarLoader';
import { roles } from '../tengilidur/containers/AddDelegate';

type CardListProps = {
  name?: string;
  rolePhoneNumber?: string;
  roleTypes?: (RoleType | null | undefined)[];
  roleTitle?: string;
  isLoading?: boolean;
  onEditClick: () => void;
  onDeleteClick: () => void;
};
export const CardList = ({
  name,
  rolePhoneNumber,
  roleTypes,
  roleTitle,
  isLoading,
  onEditClick,
  onDeleteClick,
}: CardListProps) => {
  const { t } = useTranslation('stillingar');

  return (
    <Box background="white" padding={3} style={{ opacity: isLoading ? 0.5 : 1 }}>
      <Grid gridTemplate={{ sm: 4, lg: 12 }} rowGap={[2, 2, 4]} alignItems="center">
        <GridItem gridColumn={{ sm: 'span4', lg: 'span3' }}>
          <Text variant="pMediumBold">{name ?? '--'}</Text>
        </GridItem>
        <GridItem gridColumn={{ sm: 'span4', lg: 'span2' }}>
          <Text variant="pMediumBold">{roleTitle || 'Ekkert'}</Text>
        </GridItem>
        <GridItem gridColumn={{ sm: 'span4', lg: 'span2' }}>
          <Text variant="pMediumBold">{formatPhone(rolePhoneNumber ?? '') ?? '--'}</Text>
        </GridItem>
        <GridItem gridColumn={{ sm: 'span3' }}>
          <Box display="flex" width="100%" gap={1}>
            {roleTypes?.map((role, i) => {
              return (
                role && (
                  <Pill
                    key={`__${i}_${role}`}
                    color="pink"
                    text={roles.find((r) => r.value === role)?.label ?? role}
                  />
                )
              );
            })}
          </Box>
        </GridItem>
        <GridItem gridColumn={{ sm: 'span2' }}>
          <Box width="100%" display="flex" justifyContent="flex-end">
            <Menu
              color="pink"
              label={`Edit menu for ${name}`}
              items={[
                {
                  text: t('contactsTab.edit'),
                  onClick: () => onEditClick(),
                },
                {
                  text: t('contactsTab.delete'),
                  onClick: () => onDeleteClick(),
                },
              ]}
              disclosure={
                <IconButton color="black100" icon="dotsHorizontal" hiddenButtonText="More button" />
              }
            />
          </Box>
        </GridItem>
      </Grid>
    </Box>
  );
};

export const Contacts = () => {
  const { t } = useTranslation(['stillingar', 'errors']);
  const router = useRouter();
  const [errorMesage, setErrorMessage] = useState<string>();
  const [name, setName] = useState('');
  const customerId: string = (router.query.customerId as string) ?? '';

  const { data, loading, error, refetch, networkStatus } = useCustomerDelegatesQuery({
    variables: { input: { id: customerId } },
  });

  const [removeDelegateMutation, { loading: loadingRemove }] = useRemoveDelegateMutation({
    refetchQueries: [{ query: CUSTOMER, variables: { input: { id: customerId } } }],
    awaitRefetchQueries: true,
  });

  useEffect(() => {
    if (data && data?.customer?.name) setName(data.customer.name);
    else setName('þér');
  }, [data]);

  const handleRemoveDelegate = async (delegateId: string) => {
    setErrorMessage(undefined);
    try {
      if (delegateId) {
        const { data: removeDelegateData } = await removeDelegateMutation({
          variables: { input: { id: customerId, delegateId: delegateId } },
        });
        if (removeDelegateData?.removeDelegate?.error) {
          setErrorMessage(error?.message as string);
        }
      }
    } catch (e) {
      if (error instanceof Error) {
        setErrorMessage(error.message);
      }
    }
  };

  const handleEditDelegate = (delegateId: string) => {
    router.push(`/beta/${customerId}/stillingar/tengilidur?step=1&delegateId=${delegateId}`);
  };

  if (error || loading)
    return (
      <Box marginTop={[5, 20]}>
        <ErrorBanner
          eyebrowTexts={[
            t('errors:contact.eyebrows.1'),
            t('errors:contact.eyebrows.2'),
            t('errors:contact.eyebrows.3'),
          ]}
          titles={[
            t('errors:contact.titles.1'),
            t('errors:contact.titles.2'),
            t('errors:contact.titles.3'),
          ]}
          descriptions={[
            t('errors:contact.descriptions.1'),
            t('errors:contact.descriptions.2'),
            t('errors:contact.descriptions.3'),
          ]}
          icon="zap"
          color="attention"
          showLoading={loading || networkStatus === NetworkStatus.refetch}
          refetchButton={{
            text: t('errors:buttons.refresh'),
            icon: 'refresh',
            onClick: () => refetch(),
          }}
          loadingComponent={<StillingarLoader />}
        />
      </Box>
    );

  return (
    <>
      <Box marginTop={8} display="flex" flexDirection="column" gap={3}>
        <Box width="8/12" marginBottom={7}>
          <Text variant="pMediumRegular">
            <Trans i18nKey="stillingar:contactsTab.pageCopy">
              ..
              <strong>{{ name }}</strong>
              ...
            </Trans>
          </Text>
        </Box>
        <Box width="4/12" alignSelf="flex-end" marginBottom={3}>
          <MainButton
            renderAs="a"
            text={t('contactsTab.addDelegate')}
            dottedShadow="none"
            colorScheme="white"
            icon="add"
            wrapper={(children) => (
              <Link href={`/beta/${customerId}/stillingar/tengilidur`} passHref legacyBehavior>
                {children}
              </Link>
            )}
          />
        </Box>

        <>
          <Box paddingX={3}>
            <Grid gridTemplate={{ sm: 4, lg: 12 }} rowGap={[2, 2, 4]} alignItems="center">
              <GridItem gridColumn={{ sm: 'span4', lg: 'span3' }}>
                <Text>{t('contactsTab.tr1')}</Text>
              </GridItem>
              <GridItem gridColumn={{ sm: 'span4', lg: 'span2' }}>
                <Text>{t('contactsTab.tr2')}</Text>
              </GridItem>
              <GridItem gridColumn={{ sm: 'span4', lg: 'span2' }}>
                <Text>{t('contactsTab.tr3')}</Text>
              </GridItem>
              <GridItem gridColumn={{ sm: 'span5' }}>
                <Text>{t('contactsTab.tr4')}</Text>
              </GridItem>
            </Grid>
          </Box>
          {data?.customer?.delegates?.length ? (
            <>
              {data.customer.delegates.map((delegate, i) => {
                const customer = delegate.customer;
                const delegateId: string = delegate.id;
                return (
                  <CardList
                    key={`${delegate.id}__${i}`}
                    name={customer.name ?? ''}
                    rolePhoneNumber={delegate.rolePhoneNumber ?? ''}
                    roleTypes={delegate.roleTypes ?? undefined}
                    roleTitle={delegate.roleTitle ?? ''}
                    onEditClick={() => handleEditDelegate(delegateId)}
                    onDeleteClick={() => handleRemoveDelegate(delegateId)}
                    isLoading={loadingRemove}
                  />
                );
              })}
            </>
          ) : (
            <Box marginTop={5}>
              <Empty icon="search" title="" subtitle={t('contactsTab.noContacts')} />
            </Box>
          )}
        </>

        {errorMesage && (
          <AttentionBanner
            icon="warning"
            regularText={t('contactsTab.errorTitle')}
            strongText={errorMesage}
            color="warning"
          />
        )}
      </Box>
    </>
  );
};
