import React, { useEffect, useState } from 'react';

import { scrollIntoView } from '../../helpers/utility';

import { Wrapper, PageNum, Img, Loading } from './styled';

type Props = {
  pageNum: number;
  getPdfImage: (page: number) => Promise<string>;
  renderingState: string;
};

const index: React.FC<Props> = ({
  pageNum,
  getPdfImage,
  renderingState,
}: Props) => {
  const [dataUrl, setDataUrl] = useState('');

  const getDataUrl = async (): Promise<any> => {
    const imageDataUrl = await getPdfImage(pageNum);
    setDataUrl(imageDataUrl);
  };

  const onClick = (): void => {
    const ele: HTMLElement | null = document.getElementById(`page_${pageNum}`);

    if (ele) {
      scrollIntoView(ele);
    }
  };

  useEffect(() => {
    if (renderingState === 'RENDERING') {
      getDataUrl();
    }
  }, [renderingState]);

  return (
    <Wrapper id={`thumbnail_${pageNum}`}>
      <PageNum>{pageNum}</PageNum>
      {renderingState === 'RENDERING' && dataUrl ? (
        <Img src={dataUrl} onClick={onClick} />
      ) : (
        <Loading />
      )}
    </Wrapper>
  );
};

export default index;
