import React, { useState } from 'react';
import { Box, Checkbox, Icon, MainButton, Text } from '@nova-hf/ui';
import { getMaxLengthOfName } from 'beta/utils/helpers';
import MultiStepWrapper from 'containers/multiStepWrapper/MultiStepWrapper';
import { inject, observer } from 'mobx-react';
import { useRouter } from 'next/router';
import { useSnackbar } from 'notistack';
import Authentication from 'store/authentication';
import Hradleid from 'store/hradleid';
import UI from 'store/ui';
import { IContext } from 'typings/context';
import { useAddServicepackMutation, useSubscriptionsQuery } from 'typings/graphql';
import { useTranslation } from 'utils/i18n';

const COLOR = 'pink';

type AddPackProps = {
  hradleid: Hradleid;
  authentication: Authentication;
  ui: UI;
};

type mappedSubscription = {
  name: string;
  info: string;
  id: string;
  payer?: string;
  canGetPack?: boolean;
};

const AddPack = ({ hradleid, authentication, ui }: AddPackProps) => {
  const { t } = useTranslation('multi');
  const { enqueueSnackbar } = useSnackbar();
  const [checkedSubIds, setCheckedSubIds] = useState<string[]>();
  const [performNextMonth, setPerformNextMonth] = useState(false);
  const router = useRouter();
  const ssn = router?.query?.ssn;
  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: subId,
        id: subId,
        payer: subscription?.accountSsn,
        canGetPack: !!subscription?.rateplan?.availableServicepacks?.find(
          (pack) => pack?.name === 'Hringt til útlanda',
        ),
      };
    });
  };

  const mappedSubs = mapSubsToUsernamesAndInfo();
  const subsWhereCustomerIsNotPayerOrCantGetPAck = mappedSubs?.filter(
    (sub) => sub.payer !== ssn || !sub.canGetPack,
  );
  const filteredSubIds = subsWhereCustomerIsNotPayerOrCantGetPAck?.map((sub) => sub.id);
  const getCheckedSubs = (subIds: Array<string>) => {
    setCheckedSubIds(subIds);
  };
  const addInput = (subscription: mappedSubscription) => {
    const isChecked = checkedSubIds?.some((checkedSub) => checkedSub === subscription?.id);
    if (isChecked) {
      return {
        servicepackId: 'S2102',
        activateNextMonth: performNextMonth,
      };
    }
    return null;
  };

  const [addPackToService, { loading }] = useAddServicepackMutation({
    onCompleted: (data) => {
      enqueueSnackbar(t('addPack.success'), {
        variant: 'success',
      });

      if (data) {
        router.push(`/${router.query.ssn}/fjoldaskraning`);
        hradleid?.incrementTrigger();
        ui.setHasMultiMenu(false);
      }
    },
    onError(error) {
      enqueueSnackbar(t('addPack.error') + error.message, {
        variant: 'error',
      });
    },
  });

  const handleButtonClick = async (subscriptions: mappedSubscription[]) => {
    for (const subscription of subscriptions) {
      const useInput = addInput(subscription);

      if (useInput) {
        await addPackToService({
          variables: { input: useInput, subscriptionId: subscription?.id },
        });
      }
    }
  };

  return (
    <MultiStepWrapper
      hradleid={hradleid}
      color={COLOR}
      getMappedSubs={mappedSubs}
      disabledSubIds={filteredSubIds ?? []}
      sendCheckedToChild={getCheckedSubs}
      title={t('addPack.title')}
      firstRowTitle={t('multi:headers.user')}
      secondRowTitle={t('multi:multi.phoneNumber')}
      icon="mobilePlus"
      customerName={customerName ?? ''}
    >
      <Box display="flex" flexDirection="column" gap={3}>
        <Text color="black100" variant="h4">
          {t('addPack.title')}
        </Text>
        <Text color="black100">{t('addPack.description')}</Text>
        <Box
          display="flex"
          flexDirection="row-reverse"
          alignItems="center"
          justifyContent="space-between"
          marginTop={10}
        >
          <Box display="flex" flexDirection="column" gap={3} width="4/12">
            <Checkbox
              label={t('addPack.nextMonth')}
              isChecked={performNextMonth}
              type="checked"
              color={COLOR}
              onChange={() => {
                setPerformNextMonth(!performNextMonth);
              }}
            />
            <MainButton
              text={t('addPack.confirm')}
              onClick={() => (mappedSubs ? handleButtonClick(mappedSubs) : undefined)}
              dottedShadow="none"
              color="pink"
              isLoading={loading}
              isDisabled={!subscriptions}
            />
          </Box>
        </Box>
        {filteredSubIds && filteredSubIds.length > 0 && (
          <Box display="flex" flexDirection="row" alignItems="center" gap={1}>
            <Icon icon="info" color="warning" />
            <Text>{t('addPack.filtered')}</Text>
          </Box>
        )}
      </Box>
    </MultiStepWrapper>
  );
};

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

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