import * as React from 'react';
import { useMutation } from '@apollo/client';
import { Button, Col, Confirmation, PaymentFooter } from '@nova-hf/ui';
import DateSVG from 'assets/svg/date.svg';
import { EffectTime } from 'containers/checkout/steps';
import { ADD_SERVICEPACK } from 'graphql/mutations/servicepacks';
import { inject, observer } from 'mobx-react';
import { useRouter } from 'next/router';
import { useSnackbar } from 'notistack';
import { formatPrice } from 'utils/helpers';
import { useTranslation } from 'utils/i18n';

interface IConfirmChangeProps {
  change?: any;
  color: string;
  subscriptionId: string;
}

const ConfirmServicepackChange = ({ change, color, subscriptionId }: IConfirmChangeProps) => {
  const {
    activateNextMonth,
    selectedServicepack,
    resetChangeFlow,
    packToChange,
    checkEffectTime,
    allowChangeLater,
  } = change;
  const isUnlimitedWithFiber = selectedServicepack?.id === 'S3009';

  const { enqueueSnackbar } = useSnackbar();
  const [addServicepack, { loading }] = useMutation(ADD_SERVICEPACK);
  const { t } = useTranslation('change');
  const router = useRouter();

  if (checkEffectTime && allowChangeLater && !isUnlimitedWithFiber) {
    return <EffectTime color={color} />;
  }

  const onSubmit = async () => {
    const input = {
      servicepackId: selectedServicepack.id,
      activateNextMonth,
    };

    try {
      await addServicepack({ variables: { input, subscriptionId } });

      resetChangeFlow();

      enqueueSnackbar(t('steps.confirmation.success'), {
        variant: 'success',
      });

      router
        .push(`/${router.query.ssn}/thjonusta/${subscriptionId}`)
        .then(() => window.scrollTo(0, 0));
    } catch (e) {
      enqueueSnackbar(t('steps.confirmation.error'), {
        variant: 'error',
      });
    }
  };

  return (
    <Col col={6} push={3} base={12}>
      <Confirmation
        title={t('steps.confirmation.heading')}
        description={t('steps.confirmation.info', {
          effect: activateNextMonth
            ? t('steps.confirmation.nextEffect')
            : t('steps.confirmation.nowEffect'),
        })}
        current={{
          label: t('steps.confirmation.current'),
          value:
            packToChange &&
            `${packToChange.info.shortTitle}: ${formatPrice(packToChange.info.price)}`,
        }}
        selected={{
          label: t('steps.confirmation.new'),
          value:
            selectedServicepack &&
            `${selectedServicepack.shortTitle}: ${formatPrice(selectedServicepack.price)}`,
        }}
        icon={<DateSVG />}
      />

      <PaymentFooter>
        <Button background={color} loading={loading} onClick={onSubmit}>
          {t('steps.confirmation.button')}
        </Button>
      </PaymentFooter>
    </Col>
  );
};

export default inject('change')(observer(ConfirmServicepackChange));
