import React, { useState } from 'react';
import { getMaxLengthOfName } from 'beta/utils/helpers';
import MultiStepWrapper from 'containers/multiStepWrapper/MultiStepWrapper';
import { inject, observer } from 'mobx-react';
import Authentication from 'store/authentication';
import Hradleid from 'store/hradleid';
import UI from 'store/ui';
import { IContext } from 'typings/context';
import { useSubscriptionsQuery } from 'typings/graphql';
import { useTranslation } from 'utils/i18n';

import UserPage from '../../thjonusta/stillingar/notandi';

const COLOR = 'pink';

type NotendabreytingProps = {
  hradleid: Hradleid;
  authentication: Authentication;
  ui: UI;
  ssn: string;
};

const Notendabreyting = ({ hradleid, authentication, ssn }: NotendabreytingProps) => {
  const { t } = useTranslation(['multi']);
  const [checkedSubIds, setCheckedSubIds] = useState<string[]>();
  const { accountInput } = authentication;
  const { data } = useSubscriptionsQuery({
    variables: {
      subscriptionsInput: {
        onlyActive: true,
        forBulkMethods: true,
        perPage: 1000,
      },
      accountInput,
    },
    ssr: false,
  });

  const subscriptions = data?.me?.subscriptions?.subscriptions;
  const customerName = data?.me?.name;

  const mapSubsToUsernamesAndInfo = () => {
    return hradleid?.subscriptionIds?.map((subId) => {
      const subscription = subscriptions?.find((sub) => sub?.subscriptionId === subId);
      const username = subscription?.name;
      const MAX = getMaxLengthOfName();
      const truncatedName =
        username && username.length > MAX ? `${username.slice(0, MAX)}...` : username;

      return {
        name: truncatedName as string,
        info: subscription?.subscriptionId,
        id: subId,
        payer: subscription?.accountSsn,
      };
    });
  };

  const mappedSubs = mapSubsToUsernamesAndInfo();
  const subsWhereCustomerIsNotPayer = mappedSubs?.filter((sub) => sub.payer !== ssn);
  const filteredSubIds = subsWhereCustomerIsNotPayer?.map((sub) => sub.id);
  const getCheckedSubs = (subIds: Array<string>) => {
    setCheckedSubIds(subIds);
  };

  return (
    <MultiStepWrapper
      hradleid={hradleid}
      color={COLOR}
      getMappedSubs={mappedSubs}
      disabledSubIds={filteredSubIds ?? []}
      sendCheckedToChild={getCheckedSubs}
      title={'Notendabreyting'}
      firstRowTitle={t('headers.user')}
      secondRowTitle={'Símanúmer'}
      icon="userCircle"
      customerName={customerName ?? ''}
    >
      <UserPage subscriptionIds={checkedSubIds} />
    </MultiStepWrapper>
  );
};

Notendabreyting.getInitialProps = ({ pathname, query }: IContext) => {
  return {
    pathname,
    ssn: query.ssn,
    namespacesRequired: ['multi'],
  };
};

export default inject('hradleid', 'authentication', 'ui')(observer(Notendabreyting));
