import * as React from 'react';
import Router from 'next/router';
import { observer, inject } from 'mobx-react';
import { get } from 'lodash';
import { withSnackbar, WithSnackbarProps } from 'notistack';
import { Button as MaterialButton } from '@material-ui/core';
import { Mutation } from '@apollo/client/react/components';

import UsagePack from 'store/models/UsageInfo';
import Connection from 'store/models/Connection';
import DateSVG from 'assets/svg/date.svg';
import { withTranslation, WithTranslation } from 'utils/i18n';

import { REMOVE_SERVICEPACK } from 'graphql/mutations/servicepacks';
import { REMOVE_AUTOREFILL } from 'graphql/mutations/autorefills';

import { ProfileConfirmation } from 'components/profile-detail/ProfileConfirmation';
import { IAutoRefill } from 'typings';
import { REMOVE_CONNECTION } from 'graphql/mutations/connections';
import { REMOVE_SLOT } from 'graphql/mutations/slots';
import { formatDate } from 'utils/helpers';

import Change from 'store/change';

interface IConfirmCancelProps extends WithTranslation, WithSnackbarProps {
  change?: Change;
  color: string;
  subscriptionId: string;
  returnLink: string;
}

interface IConfirmCancelState {
  status: string;
  message: string;
}

class ConfirmCancel extends React.Component<IConfirmCancelProps, IConfirmCancelState> {
  state: IConfirmCancelState = {
    message: '',
    status: '',
  };

  action = (key: any, closeSnackbar: any) => {
    const { t } = this.props;

    return (
      <MaterialButton
        onClick={() => {
          closeSnackbar(key);
        }}
      >
        {t('common:notification.dismiss')}
      </MaterialButton>
    );
  };

  componentDidMount() {
    const { change, returnLink } = this.props;
    if (!change) return;
    const { autoRefillToChange, packToChange, connectionToChange, visitToChange } = change;

    if (!autoRefillToChange && !packToChange && !connectionToChange && !visitToChange) {
      Router.push(returnLink);
    }
  }

  onCancelPack = async (removeServicepack: any, pack: UsagePack) => {
    const { t, change, returnLink } = this.props;
    if (!change) return;

    const { selectedProfile, resetChangeFlow } = change;
    const input = {
      servicepackId: pack.servicepackId,
      activateNextMonth: false,
    };

    try {
      await removeServicepack({
        variables: { input, subscriptionId: selectedProfile?.subscriptionId },
      });

      resetChangeFlow();
      Router.push(returnLink);
      this.onMessage(t('common:notification.success'), 'success');
    } catch (e) {
      this.onMessage(t('detail.errorMessage'), 'error');
    }
  };

  onCancelAutoRefill = async (removeAutoRefill: any, autoRefill: IAutoRefill) => {
    const { t, change, returnLink } = this.props;
    if (!change) return;
    const { selectedProfile, resetChangeFlow } = change;

    try {
      await removeAutoRefill({
        variables: {
          input: { autoRefillId: autoRefill.id },
          subscriptionId: selectedProfile?.subscriptionId,
        },
      });

      resetChangeFlow();
      Router.push(returnLink);

      this.onMessage(t('common:notification.success'), 'success');
    } catch (e) {
      this.onMessage(t('detail.errorMessage'), 'error');
    }
  };

  onCancelConnection = async (removeConnection: any, connection: Connection) => {
    const { t, change, returnLink } = this.props;
    if (!change) return;

    const { selectedProfile, resetChangeFlow } = change;

    try {
      const { data } = await removeConnection({
        variables: {
          input: { connectionId: connection.id },
          subscriptionId: selectedProfile?.subscriptionId,
        },
      });
      const message = get(data, ['removeConnection', 'error', 'message']);

      if (message) {
        this.onMessage(`${t('detail.cancel.connection.errorMessage')}: ${message}`, 'error');
      } else {
        resetChangeFlow();
        Router.push(returnLink);

        this.onMessage(t('common:notification.success'), 'success');
      }
    } catch (e) {
      this.onMessage(t('detail.cancel.connection.errorMessage'), 'error');
    }
  };

  onRemoveVisit = async (removeVisitSlot: any, subscriptionId: string) => {
    const { t, change, returnLink } = this.props;
    if (!change) return;

    const { resetChangeFlow } = change;

    try {
      const { data } = await removeVisitSlot({ variables: { subscriptionId } });
      const message = get(data, ['removeVisitSlot', 'error', 'message']);

      if (message) {
        this.onMessage(`${t('detail.cancel.visit.errorMessage')}: ${message}`, 'error');
      } else {
        resetChangeFlow();
        Router.push(returnLink);

        this.onMessage(t('common:notification.success'), 'success');
      }
    } catch (e) {
      this.onMessage(`${t('detail.cancel.visit.errorMessage')}: ${e}`, 'error');
    }
  };

  onMessage(message: string, variant: 'default' | 'error' | 'success' | 'warning' | 'info') {
    const { enqueueSnackbar, closeSnackbar } = this.props;

    enqueueSnackbar(message, {
      variant,
      action: (key) => this.action(key, closeSnackbar),
    });

    if (variant === 'error') this.setState({ message });
  }

  render() {
    const { t, change, color, subscriptionId } = this.props;
    if (!change) return;

    const { autoRefillToChange, packToChange, connectionToChange, visitToChange } = change;
    const { message } = this.state;

    if (autoRefillToChange) {
      return (
        <Mutation mutation={REMOVE_AUTOREFILL}>
          {(removeAutoRefill: any, { loading }: any) => {
            return (
              <ProfileConfirmation
                color={color}
                title={t('detail.cancel.confirmation.heading')}
                description={t('detail.cancel.confirmation.description')}
                icon={<DateSVG />}
                errorMessage={message}
                buttonLoading={loading}
                buttonText={t('detail.cancel.confirmation.button')}
                onClick={() => {
                  this.onCancelAutoRefill(removeAutoRefill, autoRefillToChange);
                }}
                posCenter
              />
            );
          }}
        </Mutation>
      );
    }

    if (connectionToChange) {
      return (
        <Mutation mutation={REMOVE_CONNECTION}>
          {(removeConnection, { loading }) => {
            return (
              <ProfileConfirmation
                color={color}
                title={t('detail.cancel.connection.heading')}
                description={t('detail.cancel.connection.description')}
                icon={<DateSVG />}
                errorMessage={message}
                buttonLoading={loading}
                buttonText={t('detail.cancel.connection.button')}
                onClick={() => {
                  this.onCancelConnection(removeConnection, connectionToChange);
                }}
                posCenter
              />
            );
          }}
        </Mutation>
      );
    }
    if (visitToChange) {
      const { bookDate } = visitToChange;

      return (
        <Mutation mutation={REMOVE_SLOT}>
          {(removeVisitSlot, { loading }) => {
            return (
              <ProfileConfirmation
                color={color}
                title={t('detail.cancel.visit.heading')}
                description={t('detail.cancel.visit.description', {
                  date: bookDate && formatDate(new Date(bookDate), 'd.MMM'),
                  time: bookDate && formatDate(new Date(bookDate), 'H:mm'),
                })}
                icon={<DateSVG />}
                errorMessage={message}
                buttonLoading={loading}
                buttonText={t('detail.cancel.visit.button')}
                onClick={() => {
                  this.onRemoveVisit(removeVisitSlot, subscriptionId);
                }}
                posCenter
              />
            );
          }}
        </Mutation>
      );
    }
    return (
      <Mutation mutation={REMOVE_SERVICEPACK}>
        {(removeServicepack: any, { loading }: any) => {
          return (
            <ProfileConfirmation
              color={color}
              title={t('detail.cancel.confirmation.heading')}
              description={t('detail.cancel.confirmation.description')}
              icon={<DateSVG />}
              errorMessage={message}
              buttonLoading={loading}
              buttonText={t('detail.cancel.confirmation.button')}
              onClick={() => {
                if (packToChange) this.onCancelPack(removeServicepack, packToChange as UsagePack);
              }}
              posCenter
            />
          );
        }}
      </Mutation>
    );
  }
}
export default withTranslation(['subscription', 'common'])(
  withSnackbar(inject('change')(observer(ConfirmCancel))),
);
