import React, { useEffect, useState } from 'react';
import {
  Box,
  Button,
  CheckboxDeprecated,
  CheckboxGroupDeprecated,
  Col,
  ErrorMessage,
  NumberTextBox,
  Pagination,
  PaymentSection,
  Row,
  Select,
  SubscriptionButton,
  SubscriptionButtonWrapper,
  TextBox,
} from '@nova-hf/ui';
import { MainColorType } from '@nova-hf/ui/umd/ts/src/styles/vars.css';
import { inject } from 'mobx-react';
import { useRouter } from 'next/router';
import { useSnackbar } from 'notistack';
import {
  useAddCustomerContactMutation,
  useAddCustomerMutation,
  useCustomerIdByNationalIdQuery,
  useCustomerNameByNationalIdLazyQuery,
  useMeQuery,
  useSubscriptionsQuery,
} from 'typings/graphql';
import { pages } from 'utils/helpers';
import { useTranslation } from 'utils/i18n';

interface IAddContactProps {
  authentication?: any;
  color?: string;
  onComplete?: () => void;
}

export const titles = [
  'Enginn',
  'Framkvæmdastjóri',
  'Forstjóri',
  'Tæknistjóri/kerfissstjóri',
  'Skrifstofustjóri',
  'Innkaupastjóri',
  'Mannauðsstjóri',
  'Bókari',
];

const AddExtraContact = ({
  color = 'purple',
  authentication: { accountInput },
  onComplete,
}: IAddContactProps) => {
  const { t } = useTranslation(['settings', 'common']);
  const router = useRouter();
  const nationalId = router?.query?.ssn;
  const [ssn, setSsn] = useState('');
  const [email, setEmail] = useState('');
  const [title, setTitle] = useState('');
  const [phoneNumber, setPhoneNumber] = useState('');
  const [id, setId] = useState('');
  const [billReceiver, setBillReceiver] = useState(false);
  const [hasCredit, setHasCredit] = useState(false);
  const [hasPortalAccess, setHasPortalAccess] = useState(false);
  const [totalCount, setTotalCount] = useState(0);
  const [page, setPage] = useState(1);
  const [error, setError] = useState('');
  const [needsToCreate, setNeedsToCreate] = useState(false);
  const perPage = 9;

  const { enqueueSnackbar } = useSnackbar();

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

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

  const customerId = customerData?.customerByNationalId?.id;

  const { data, loading: loadingSubscriptions } = useSubscriptionsQuery({
    variables: {
      accountInput,
      subscriptionsInput: { perPage, page },
    },
    onCompleted: (result) => {
      if (result.me?.subscriptions.pageInfo?.totalCount) {
        setTotalCount(result.me?.subscriptions.pageInfo?.totalCount);
      }
    },
  });

  const [createExtraContactMutation, { loading }] = useAddCustomerContactMutation({});
  const [addCustomer, { loading: loadingAddCustomer }] = useAddCustomerMutation({
    onCompleted: (data) => {
      if (data) {
        setId(data.addCustomer?.customer?.id);
        setPhoneNumber(data.addCustomer?.customer?.primaryPhoneNumber);
        setEmail(data.addCustomer?.customer?.email);
      }
    },
  });

  const [getCustomerInfo, { loading: loadingCustomerInfo }] = useCustomerNameByNationalIdLazyQuery({
    onCompleted(data) {
      if (data?.customerByNationalId?.id) setId(data.customerByNationalId.id);
      if (!data.customerByNationalId?.id) {
        setNeedsToCreate(true);
      }

      if (data?.customerByNationalId?.primaryPhoneNumber)
        setPhoneNumber(data.customerByNationalId?.primaryPhoneNumber);
    },
    onError() {
      setNeedsToCreate(true);
    },
  });

  const onSubmit = async (e?: React.FormEvent) => {
    setError('');

    if (e) {
      e.preventDefault();
    }

    await addExtraContact(ssn, email);
  };
  const onSelectPage = (page: number) => {
    if (page < 1 || page > pages(totalCount, perPage)) return null;
    setPage(page);
  };

  const onSelectContact = async (contactSsn: string, contactEmail: string) => {
    await getCustomerInfo({
      variables: { input: { nationalId: contactSsn } },
    });
    setEmail(contactEmail);
    setSsn(contactSsn);
  };

  const addExtraContact = async (contactSsn: string, contactEmail?: string) => {
    if (!id && needsToCreate) {
      try {
        await addCustomer({
          variables: {
            input: {
              nationalId: contactSsn,
              email: contactEmail ?? email,
              primaryPhoneNumber: phoneNumber,
            },
          },
        });
      } catch (error) {
        if (error instanceof Error) {
          setError('Viðskiptavinur ekki til og gekk ekki að stofna.');
        }
      }
    }
    if (!customerId) {
      try {
        await addCustomer({
          variables: {
            input: {
              nationalId: nationalId?.toString() ?? '',
            },
          },
        });
        customerDataRefetch();
      } catch (error) {
        if (error instanceof Error) {
          setError('Viðskiptavinur ekki til og gekk ekki að stofna.');
        }
      }
    }
    if (contactSsn && !loadingAddCustomer && id) {
      try {
        const { data: contactData } = await createExtraContactMutation({
          variables: {
            input: {
              id: customerId ?? nationalId,
              emailAddress: contactEmail ?? email,
              phoneNumber: phoneNumber,
              contactTitle: title,
              contactId: id,
              canPurchaseOnCredit: hasCredit,
              hasPortalAccess: hasPortalAccess,
              receivesInvoiceEmails: billReceiver,
            },
          },
        });

        if (!contactData) {
          setError('Ekki tókst að bæta við tengilið');
          return;
        }

        enqueueSnackbar(`${ssn} ${t('extraContacts.addContainer.added')}`, { variant: 'success' });
      } catch (e) {
        if (e instanceof Error) {
          setError(e.message);
        }
        return;
      }

      if (onComplete) {
        onComplete();
      }
    }
  };

  useEffect(() => {
    if (ssn.length === 10) {
      getCustomerInfo({
        variables: {
          input: {
            nationalId: ssn,
          },
        },
      });
    }
  }, [ssn]);

  return (
    <>
      <form onSubmit={onSubmit}>
        <Row>
          <PaymentSection
            fullWidth
            title={t('extraContacts.addContainer.title')}
            subtitle={t('extraContacts.addContainer.subtitle', { name: meData?.me?.name })}
          >
            <Row>
              <Col col={12}>{error && <ErrorMessage>{error}</ErrorMessage>}</Col>
              <Col col={4}>
                <NumberTextBox
                  label={t('common:forms.ssn')}
                  onChange={(e: React.FormEvent<HTMLInputElement>) =>
                    setSsn(e.currentTarget?.value.replace('-', ''))
                  }
                  required
                  value={ssn}
                  color={color}
                  errorType="ssn"
                  name="ssn"
                />
              </Col>
              <Col col={4}>
                <TextBox
                  label={t('common:forms.email')}
                  onChange={(e: React.FormEvent<HTMLInputElement>) =>
                    setEmail(e.currentTarget?.value)
                  }
                  required
                  value={email}
                  color={color}
                  type="email"
                  name="email"
                  errorType="email"
                />
              </Col>
              <Col col={4}>
                <TextBox
                  label="Símanúmer"
                  onChange={(e: React.FormEvent<HTMLInputElement>) =>
                    setPhoneNumber(e.currentTarget?.value)
                  }
                  value={phoneNumber}
                  color={color}
                  type="phoneNumber"
                  name="phoneNumber"
                  errorType="phoneNumber"
                />
              </Col>
              <Col col={4}>
                <Select
                  label="Titill"
                  onChange={(e) => setTitle(e.currentTarget?.value)}
                  value={title}
                  name="title"
                >
                  {titles.map((t, index) => {
                    return (
                      <option key={index} value={t} {...(title === t && { selected: true })}>
                        {t}
                      </option>
                    );
                  })}
                </Select>
              </Col>
              <Col col={4}>
                <Button
                  big
                  fill
                  arrowRight
                  loading={loading || loadingCustomerInfo}
                  background={color}
                >
                  Bæta við
                </Button>
              </Col>
              <Col col={9}>
                <CheckboxGroupDeprecated name="paymentType" color={color} spacing>
                  <CheckboxDeprecated
                    onChange={(e: React.FormEvent<HTMLInputElement>) =>
                      setBillReceiver(e.currentTarget?.checked)
                    }
                    color={color}
                  >
                    {t('extraContacts.addContainer.sendBill')}
                  </CheckboxDeprecated>
                  <CheckboxDeprecated
                    onChange={(e: React.FormEvent<HTMLInputElement>) =>
                      setHasPortalAccess(e.currentTarget?.checked)
                    }
                    color={color}
                  >
                    Hefur aðgang að stólnum
                  </CheckboxDeprecated>
                  <CheckboxDeprecated
                    onChange={(e: React.FormEvent<HTMLInputElement>) =>
                      setHasCredit(e.currentTarget?.checked)
                    }
                    color={color}
                  >
                    Má setja í reikning
                  </CheckboxDeprecated>
                </CheckboxGroupDeprecated>
              </Col>
            </Row>
          </PaymentSection>
        </Row>
      </form>

      <SubscriptionButtonWrapper title={t('extraContacts.addContainer.chooseTitle')}>
        {data?.me?.subscriptions.subscriptions?.map((subscription) => (
          <SubscriptionButton
            key={subscription.subscriptionId}
            title={subscription.name}
            lines={[subscription.email, subscription.ssn]}
            color={color}
            fill
            icon="user"
            onClick={() => onSelectContact(subscription.ssn, subscription?.email ?? '')}
          />
        ))}
        {loadingSubscriptions &&
          Array(9)
            .fill(0)
            .map((_, i) => (
              <SubscriptionButton
                key={i}
                title="..."
                lines={['...', '...']}
                color={color}
                fill
                icon="user"
                loading
              />
            ))}
      </SubscriptionButtonWrapper>
      {pages(totalCount, perPage) > 1 && (
        <Box display="flex" placeItems="center" width="100%" paddingY={3}>
          <Pagination
            color={color as MainColorType}
            currentPage={page}
            onNext={(n) => onSelectPage(n + 1)}
            onPage={(n) => onSelectPage(n)}
            onPrev={(n) => onSelectPage(n - 1)}
            pages={pages(totalCount, perPage)}
          />
        </Box>
      )}
    </>
  );
};

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