import { useEffect } from 'react';
import { useIdleTimer } from 'react-idle-timer';

import { useDialogLayer } from '@material-hu/components/layers/Dialogs';

import { logEvent } from 'src/config/logging';
import { useAuth } from 'src/contexts/JWTContext';
import { withHuGoTheme } from 'src/hooks/useHuGoTheme';
import { EventName } from 'src/types/amplitude';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { clearInactivityStorage } from './utils';

const InactivityTimer = () => {
  const { logout, instance } = useAuth();
  const { t } = useLokaliseTranslation('errors');
  const { openDialog, closeDialog } = useDialogLayer();

  const onIdle = async () => {
    logEvent(EventName.USER_LOGOUT_INACTIVITY);
    await logout!(true);
    openDialog({
      title: t('session.expired.title'),
      textBody: t('session.expired.description'),
      primaryButtonProps: {
        children: t('session.log_in'),
        onClick: () => closeDialog(),
      },
    });
    clearInactivityStorage();
  };

  const timeout = 1000 * 60 * (instance?.userInactivity || 0);
  const disabled = !timeout;

  useEffect(() => {
    if (!disabled) {
      // user reopened the tab or logged back in
      const nextLogout = parseInt(localStorage.getItem('nextLogout') || '0');
      if (!nextLogout) {
        return;
      }
      if (nextLogout < new Date().getTime()) {
        onIdle();
      }
    }
  }, [disabled]);

  const saveNextLogout = () => {
    localStorage.setItem(
      'nextLogout',
      (new Date().getTime() + timeout).toString(),
    );
  };

  useIdleTimer({
    timeout,
    onAction: saveNextLogout,
    onIdle,
    throttle: 1000, // run onAction once per second at the most
    startManually: disabled,
    crossTab: true, // using react-idle-timer v5.3 because crossTab doesn't work on newer versions
  });

  return null;
};

export default withHuGoTheme(InactivityTimer);
