import React, { useEffect, useState } from 'react';
import { Subscription, interval } from 'rxjs';
import { take } from 'rxjs/operators';

import { useTranslation } from 'react-i18next';
import { useToasts } from 'react-toast-notifications';

import useStore from '../store';
import { saveFile } from '../apis';

const index: React.FC = () => {
  const { t } = useTranslation('toast');
  const [{ info, annotations, initiated }] = useStore();
  const [isSaved, setSaved] = useState(false);
  const [isSaving, setSaving] = useState(false);
  const { addToast, removeAllToasts } = useToasts();
  let subscription: Subscription | null = null;

  useEffect(() => {
    if ((info.id && annotations.length) || (initiated && !annotations.length)) {
      if (subscription) subscription.unsubscribe();

      setSaved(false);
      setSaving(true);
      const observable = interval(1000);

      const data = {
        transaction_id: info.id,
        append_objects: annotations,
      };

      subscription = observable.pipe(take(4)).subscribe((x: number) => {
        if (x === 3) {
          saveFile(info.token, data).then(() => {
            setSaving(false);
            setSaved(true);
          });
        }
      });
    }

    return (): void => {
      if (subscription) subscription.unsubscribe();
    };
  }, [info, annotations]);

  useEffect(() => {
    removeAllToasts();

    if (isSaving) {
      addToast(t('saving'), {
        appearance: 'info',
        placement: 'bottom-center',
      });
    }
    if (!isSaving && isSaved) {
      addToast(t('saved'), {
        appearance: 'success',
        placement: 'bottom-center',
        autoDismiss: true,
        onDismiss: () => {
          removeAllToasts();
        },
      });
    }
  }, [isSaved, isSaving]);

  return <></>;
};

export default index;
