import * as React from 'react';
import { Button, CheckboxDeprecated, PaymentSection, Select, Text } from '@nova-hf/ui';
import SVGClose from 'assets/svg/close.svg';
import Wrapper from 'components/app-layout/Wrapper';
import IconButton from 'components/icon-button/IconButton';
import LinkWrapper from 'components/link-wrapper/LinkWrapper';
import LoadingTableBody from 'components/table/LoadingTableBody';
import Table from 'components/table/Table';
import TableBody from 'components/table/TableBody';
import TableCell from 'components/table/TableCell';
import TableHead from 'components/table/TableHead';
import TableRow from 'components/table/TableRow';
import { inject } from 'mobx-react';
import { useRouter } from 'next/router';
import { useSnackbar } from 'notistack';
import Authentication from 'store/authentication';
import UI from 'store/ui';
import {
  useChangeCustomerContactMutation,
  useCustomerContactsQuery,
  useCustomerIdByNationalIdQuery,
  useMeQuery,
  useRemoveCustomerContactMutation,
} from 'typings/graphql';
import { useTranslation } from 'utils/i18n';
import SEO from 'utils/SEO';

import { titles } from '../../../containers/add-extra-contact/AddExtraContact';
import Settings from '../containers/settings/Settings';

interface ITengilidirProps {
  ui?: UI;
  authentication?: Authentication;
}

const Tengilidir = ({ authentication, ui }: ITengilidirProps) => {
  const { t } = useTranslation(['settings', 'common']);

  if (!authentication || !ui) {
    return null;
  }

  const router = useRouter();
  const { accountInput } = authentication;
  const { pageColor } = ui;

  const { data: meData } = useMeQuery({ variables: { accountInput } });

  if (meData?.me?.userProfile && !meData.me.userProfile.isCompany) {
    return <div>Þessi síða er aðeins fyrir fyrirtæki</div>;
  }

  const { data: customerData } = useCustomerIdByNationalIdQuery({
    variables: {
      input: {
        nationalId: accountInput.ssn,
      },
    },
    skip: !accountInput.ssn,
  });

  const customerId = customerData?.customerByNationalId?.id;

  const { data, loading, refetch } = useCustomerContactsQuery({
    variables: {
      input: {
        id: customerId,
      },
      skip: !customerId,
    },
    fetchPolicy: 'cache-and-network',
  });
  const { enqueueSnackbar } = useSnackbar();

  const contacts = data?.customerContacts;

  const [removeExtraContactMutation, { loading: loadingRemove }] = useRemoveCustomerContactMutation(
    {},
  );

  const [changeExtraContactMutation, { loading: loadingChange }] = useChangeCustomerContactMutation(
    {},
  );

  const onRemoveClick = async (id: string, customerContactId?: string) => {
    try {
      const { data: removeData } = await removeExtraContactMutation({
        variables: { input: { id: id, contactId: customerContactId ?? '' } },
      });

      if (removeData) {
        refetch();
        enqueueSnackbar('Tókst að fjarlægja tengilið', { variant: 'success' });
      }
    } catch (e) {
      enqueueSnackbar(`${t('extraContacts.errors.remove')} ${e.message}`, { variant: 'error' });
    }
  };

  const onToggle = async (id: string, isOn: boolean, type: string) => {
    if (id && type === 'receivesInvoiceEmails') {
      try {
        const changeResult = await changeExtraContactMutation({
          variables: {
            input: {
              id: customerId ?? '',
              contactId: id,
              receivesInvoiceEmails: !isOn,
            },
          },
        });

        if (changeResult?.data) {
          refetch();
          enqueueSnackbar('Tókst að breyta tengilið', { variant: 'success' });
        }
      } catch (e) {
        enqueueSnackbar('Ekki tókst að breyta tengilið', { variant: 'error' });
      }
    }
    if (id && type === 'hasPortalAccess') {
      try {
        const changeResult = await changeExtraContactMutation({
          variables: {
            input: {
              id: customerId ?? '',
              contactId: id,
              hasPortalAccess: !isOn,
            },
          },
        });

        if (changeResult?.data) {
          refetch();
          enqueueSnackbar('Tókst að breyta tengilið', { variant: 'success' });
        }
      } catch (e) {
        enqueueSnackbar('Ekki tókst að breyta tengilið', { variant: 'error' });
      }
    }
    if (id && type === 'canPurchaseOnCredit') {
      try {
        const changeResult = await changeExtraContactMutation({
          variables: {
            input: {
              id: customerId ?? '',
              contactId: id,
              canPurchaseOnCredit: !isOn,
            },
          },
        });

        if (changeResult?.data) {
          refetch();
          enqueueSnackbar('Tókst að breyta tengilið', { variant: 'success' });
        }
      } catch (e) {
        enqueueSnackbar('Ekki tókst að breyta tengilið', { variant: 'error' });
      }
    }
  };

  const onTitleChange = async (title: string, contactId: string) => {
    if (contactId) {
      try {
        const changeResult = await changeExtraContactMutation({
          variables: {
            input: {
              id: customerId ?? '',
              contactId: contactId,
              contactTitle: title,
            },
          },
        });

        if (changeResult?.data) {
          refetch();
          enqueueSnackbar('Tókst að breyta tengilið', { variant: 'success' });
        }
      } catch (e) {
        enqueueSnackbar('Ekki tókst að breyta tengilið', { variant: 'error' });
      }
    }
  };

  return (
    <Wrapper header="dark">
      <SEO title={t('extraContacts.title')} />
      <Settings link={router.asPath} color={pageColor}>
        <PaymentSection
          fullWidth
          title={t('extraContacts.title')}
          subtitle={t('extraContacts.subtitle', { name: meData?.me?.name })}
        >
          <Button
            linkComponent={<LinkWrapper href={`/${accountInput.ssn}/stillingar/tengilidir/nyr`} />}
            arrowRight
            background={pageColor}
          >
            {t('extraContacts.addButton')}
          </Button>
        </PaymentSection>
        <PaymentSection fullWidth title={t('extraContacts.tableTitle')}>
          <Table>
            <TableHead>
              <TableCell>{t('common:forms.name')}</TableCell>
              <TableCell>Titill</TableCell>
              <TableCell>{t('common:forms.email')}</TableCell>
              <TableCell>{t('common:forms.ssn')}</TableCell>
              <TableCell>{t('extraContacts.billReceiver')}</TableCell>
              <TableCell>Aðgangur að stól</TableCell>
              <TableCell>Má setja í reikning</TableCell>
              <TableCell>{t('extraContacts.remove')}</TableCell>
            </TableHead>
            {loading && !loadingRemove ? (
              <LoadingTableBody placeholderProps={{ size: 20, width: 100 }} firstColor="dark" />
            ) : (
              <TableBody>
                {contacts?.map((contact) => (
                  <TableRow key={contact?.id}>
                    <TableCell bolder>{contact?.contactName}</TableCell>
                    <TableCell style={{ minWidth: '150px' }}>
                      <Select
                        onChange={(e) => onTitleChange(e.currentTarget?.value, contact?.id ?? '')}
                        value={contact?.contactTitle ?? 'Enginn'}
                        name="title"
                        isBold={false}
                        style={{ marginLeft: '-50px', fontSize: '12px' }}
                      >
                        {titles.map((t, index) => {
                          return (
                            <option
                              key={index}
                              value={t}
                              {...(contact?.contactTitle === t && { selected: true })}
                            >
                              <Text variant="pXSmallBold">{t}</Text>
                            </option>
                          );
                        })}
                      </Select>
                    </TableCell>
                    <TableCell>
                      {contact?.contactEmail ? (
                        <>
                          {contact.contactEmail.split('@')[0]}
                          @<br />
                          {contact.contactEmail.split('@')[1]}
                        </>
                      ) : (
                        ''
                      )}
                    </TableCell>
                    <TableCell>{contact?.contactSsn}</TableCell>
                    <TableCell align="center">
                      <CheckboxDeprecated
                        name="bill"
                        defaultChecked={contact?.receivesInvoiceEmails}
                        onChange={() => {
                          if (contact?.id) {
                            onToggle(
                              contact?.id,
                              contact?.receivesInvoiceEmails,
                              'receivesInvoiceEmails',
                            );
                          }
                        }}
                        disabled={loadingChange || loadingRemove}
                        color={pageColor}
                      />
                    </TableCell>
                    <TableCell align="center">
                      <CheckboxDeprecated
                        name="portalAccess"
                        defaultChecked={contact?.hasPortalAccess}
                        onChange={() => {
                          if (contact?.id) {
                            onToggle(contact?.id, contact?.hasPortalAccess, 'hasPortalAccess');
                          }
                        }}
                        disabled={loadingRemove || loadingChange}
                        color={pageColor}
                      />
                    </TableCell>
                    <TableCell align="center">
                      <CheckboxDeprecated
                        name="credit"
                        defaultChecked={contact?.canPurchaseOnCredit}
                        onChange={() => {
                          if (contact?.id) {
                            onToggle(
                              contact?.id,
                              contact?.canPurchaseOnCredit,
                              'canPurchaseOnCredit',
                            );
                          }
                        }}
                        disabled={loadingRemove || loadingChange}
                        color={pageColor}
                      />
                    </TableCell>
                    <TableCell align="center">
                      <IconButton
                        color="warning"
                        onClick={() => {
                          if (contact?.id && customerId) onRemoveClick(customerId, contact?.id);
                        }}
                        disabled={loadingRemove || loadingChange}
                      >
                        <SVGClose />
                      </IconButton>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            )}
          </Table>
          {loadingChange || (loadingRemove && <p>{t('extraContacts.loading')}</p>)}
        </PaymentSection>
      </Settings>
    </Wrapper>
  );
};

Tengilidir.getInitialProps = () => {
  return {
    namespacesRequired: ['settings', 'common'],
  };
};

export default inject('ui', 'authentication')(Tengilidir);
