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.FunctionComponent<Props> = ({
  pageNum,
  getPdfImage,
  renderingState,
}) => {
  const [dataUrl, setDataUrl] = useState('');

  const getDataUrl = async () => {
    const _dataUrl = await getPdfImage(pageNum);
    setDataUrl(_dataUrl);
  }

  const onClick = () => {
    const ele : HTMLElement = document.getElementById(`page_${pageNum}`)!;
    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;
