import { useEffect, useRef } from 'react';
import Debug from 'debug';
import nprogress from 'nprogress';

import type { FC } from 'react';

import styles from './styles';

const debug = Debug('songwhip/AppLoading');
const MIN_TIMEOUT = 500;

const AppLoading: FC<{ visible: boolean }> = ({ visible }) => {
  const timeoutRef = useRef<number>(null);

  useEffect(() => {
    if (visible) {
      debug('will show');

      if (timeoutRef.current) clearTimeout(timeoutRef.current);

      timeoutRef.current = setTimeout(() => {
        debug('show');
        nprogress.start();
      }, MIN_TIMEOUT) as unknown as number;
    } else {
      debug('hide');

      if (timeoutRef.current) clearTimeout(timeoutRef.current);
      nprogress.done();
    }
  }, [visible]);

  // setup
  useEffect(() => {
    nprogress.configure({ showSpinner: false });
  }, []);

  return (
    <>
      <style jsx global>
        {styles}
      </style>
    </>
  );
};

export default AppLoading;
