import * as React from 'react';
import { observer, inject } from 'mobx-react';
import { Confirmation, Button, PaymentFooter, Col } from '@nova-hf/ui';
import { useMutation } from '@apollo/client';
import { formatPrice } from 'utils/helpers';
import { useTranslation } from 'utils/i18n';
import DateSVG from 'assets/svg/date.svg';
import { useSnackbar } from 'notistack';

import { CHANGE_AUTOREFILL } from 'graphql/mutations/autorefills';
import { EffectTime } from 'containers/checkout/steps';
import { IChange } from 'store/change';
import { useRouter } from 'next/router';
interface IConfirmChangeProps {
  change?: IChange;
  color: string;
  subscriptionId: string;
}

const ConfirmAutoRefillChange = ({ change, color, subscriptionId }: IConfirmChangeProps) => {
  const {
    checkEffectTime,
    allowChangeLater,
    activateNextMonth,
    selectedRefill,
    resetChangeFlow,
    autoRefillToChange,
  } = change!;

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

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

  const onSubmit = async () => {
    if (!selectedRefill) {
      enqueueSnackbar(t('steps.confirmation.error'), {
        variant: 'error',
      });
      return;
    }

    const input = {
      refillId: selectedRefill.id,
      activateNextMonth,
    };

    try {
      const { data } = await changeAutoRefill({
        variables: { input, subscriptionId },
      });

      if (data.changeAutoRefill?.error) {
        enqueueSnackbar(
          `${t('steps.confirmation.error')}: ${data.changeAutoRefill.error.message}`,
          {
            variant: 'error',
          },
        );

        return;
      }

      resetChangeFlow();

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

      router
        .push(`${router.query.ssn}/thjonusta/${router.query.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:
            autoRefillToChange &&
            `${autoRefillToChange.info.shortTitle}: ${formatPrice(autoRefillToChange.info.price, {
              monthly: true,
            })}`,
        }}
        selected={{
          label: t('steps.confirmation.new'),
          value:
            selectedRefill &&
            `${selectedRefill.shortTitle}: ${formatPrice(selectedRefill.price, { monthly: true })}`,
        }}
        icon={<DateSVG />}
      />
      <PaymentFooter>
        <Button background={color} loading={loading} onClick={onSubmit}>
          {t('steps.confirmation.button')}
        </Button>
      </PaymentFooter>
    </Col>
  );
};

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