import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';

import { logEvent } from 'src/config/logging';
import usePrevious from 'src/hooks/usePrevious';
import { EventName } from 'src/types/amplitude';
import { getModule } from 'src/utils/amplitude';

let startTime = new Date();

const useTimeInModules = () => {
  const currentLocation = useLocation();

  const previousLocation = usePrevious(currentLocation);

  const currentModule = getModule(currentLocation);
  const previousModule = getModule(previousLocation);

  if (currentModule !== previousModule) {
    const endTime = new Date();

    const timeToTrack = endTime.getTime() - startTime.getTime();

    if (previousModule) {
      logEvent(EventName.USER_MODULE_USE, {
        module: previousModule,
        screenTime: timeToTrack,
      });
    }

    startTime = new Date();
  }

  useEffect(() => {
    const startCount = () => {
      startTime = new Date();
    };

    const stopCount = () => {
      const endTime = new Date();
      const timeToTrack = endTime.getTime() - startTime.getTime();
      if (currentModule) {
        logEvent(EventName.USER_MODULE_USE, {
          module: currentModule,
          screenTime: timeToTrack,
        });
      }
    };

    window.addEventListener('focus', startCount);
    window.addEventListener('blur', stopCount);
    window.addEventListener('beforeunload', stopCount);

    return () => {
      window.removeEventListener('focus', startCount);
      window.removeEventListener('blur', stopCount);
      window.removeEventListener('beforeunload', stopCount);
    };
  }, [currentModule]);

  return null;
};

export default useTimeInModules;
