import React from 'react';

interface UseLoadImagesOptions {
  onSuccess?(image: HTMLImageElement): void;
  onError?(): void;
}

const initialLoadState = {
  isLoading: true,
  isSuccess: false,
  isError: false,
};

export function useLoadImage(
  src: string,
  { onSuccess, onError }: UseLoadImagesOptions = {},
) {
  const imageRef = React.useRef<HTMLImageElement>(new window.Image());
  const [loadState, setLoadState] = React.useState(initialLoadState);

  React.useEffect(() => {
    setLoadState(initialLoadState);
    imageRef.current.src = src;
  }, [src]);

  imageRef.current.addEventListener('load', () => {
    setLoadState({
      isLoading: false,
      isError: false,
      isSuccess: true,
    });

    if (onSuccess) {
      onSuccess(imageRef.current);
    }
  });

  imageRef.current.addEventListener('error', () => {
    setLoadState({
      isLoading: false,
      isSuccess: false,
      isError: true,
    });

    if (onError) {
      onError();
    }
  });

  return {
    ...loadState,
    image: imageRef.current,
  };
}
