import { useEffect } from 'react';

import { logEvent } from 'src/config/logging';
import { EventName } from 'src/types/amplitude';

const useTimeInScreen = (
  eventName: EventName | null | undefined,
  eventProperties: Record<string, any>,
): null => {
  useEffect(() => {
    let startTime = new Date();
    let endTime = null;

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

    const stopCount = () => {
      endTime = new Date();
      const timeToTrack = endTime.getTime() - startTime.getTime();
      if (eventName && eventProperties) {
        logEvent(eventName, { ...eventProperties, screenTime: timeToTrack });
      }
    };

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

    return () => {
      endTime = new Date();

      const timeToTrack = endTime.getTime() - startTime.getTime();
      if (eventName && eventProperties) {
        logEvent(eventName, { ...eventProperties, screenTime: timeToTrack });
      }
      window.removeEventListener('focus', startCount);
      window.removeEventListener('blur', stopCount);
      window.removeEventListener('beforeunload', stopCount);
    };
  }, [eventName, eventProperties]);

  return null;
};

export default useTimeInScreen;
